反斜杠转义字符串的解码器

发布于 2024-10-03 06:48:50 字数 893 浏览 4 评论 0原文

PHP 中处理解码字符串的正确方法是什么,例如:

Test1 \\ Test2 \n Test3 \\n Test4 \abc

所需的输出是:

Test \ Test2 (linebreak) Test3 \n Test4 abc

我尝试过的一件事是:

str_replace(array('\\\\','\\n','\\'), array('\\',"\n",''), $str);

但这不起作用,因为它将运行替换两次,这会导致

\\n

:无论如何解码为换行符。

所以我在想这样的事情:

$offset = 0;
$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
while(($pos = strpos($str,'\\', $offset)) !== false) {

  $char = $str[$pos+1];
  if ($char=="n" || $char=="N") {
     // Insert a newline and eat 2 characters
     $str = substr($str,0,$pos-1) . "\n" . substr($str,$pos+2);
  } else {
     // eat slash
     $str = substr($str,0,$pos-1) . substr($str,$pos+1);
  }
  $offset=$pos+1;

}

这似乎可行,但我想知道是否有一个内置程序可以完全做到这一点,但我完全错过了它,或者是一种更好/更紧凑的方式来完成此操作。

What is the correct way in PHP to deal with decoding strings, such as these:

Test1 \\ Test2 \n Test3 \\n Test4 \abc

The desired output is:

Test \ Test2 (linebreak) Test3 \n Test4 abc

One thing I've tried was:

str_replace(array('\\\\','\\n','\\'), array('\\',"\n",''), $str);

But that doesn't work, because it will run the replacing twice, which causes:

\\n

To be decoded as a linebreak anyway.

So I was thinking something like this:

$offset = 0;
$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
while(($pos = strpos($str,'\\', $offset)) !== false) {

  $char = $str[$pos+1];
  if ($char=="n" || $char=="N") {
     // Insert a newline and eat 2 characters
     $str = substr($str,0,$pos-1) . "\n" . substr($str,$pos+2);
  } else {
     // eat slash
     $str = substr($str,0,$pos-1) . substr($str,$pos+1);
  }
  $offset=$pos+1;

}

This seems to work, but I was wondering if there's maybe a built-in that does exactly this and I completely missed it, or a better/more compact way altogether to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

檐上三寸雪 2024-10-10 06:48:50

stripcslashes() 几乎有效,只是它不会' t 识别 \a 并跳过它:(

$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
echo stripcslashes($str);

输出这个...

Test1 \ Test2 
 Test3 \n Test4 bc

stripcslashes() almost works, except that it won't recognize \a and skips it :(

$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
echo stripcslashes($str);

outputs this...

Test1 \ Test2 
 Test3 \n Test4 bc
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文