1

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;

}

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

4

1 回答 1

2

stripcslashes() 几乎可以工作,只是它无法识别 \a 并跳过它:(

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

输出这个...

Test1 \ Test2 
 Test3 \n Test4 bc
于 2010-11-21T20:15:10.533 回答