1
什麼是PHP正確的方式來處理解碼字符串,如這些:解碼器對反斜槓轉義字符串
Test1 \\ Test2 \n Test3 \\n Test4 \abc
所需的輸出是:
Test \ Test2 (linebreak) Test3 \n Test4 abc
有一件事我已經嘗試是:
str_replace(array('\\\\','\\n','\\'), array('\\',"\n",''), $str);
但是,這並不工作,因爲它將運行兩次更換,這會導致:
\\n
無論如何都要作爲linebreak解碼。
所以我想是這樣的:
$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;
}
這似乎是工作,但我想知道是否有可能是內置的正是這一點,我完全錯過了它,或者更好/更完全緊湊的方式來做到這一點。
這可能是足夠接近的有力競爭者:)不知道我是否需要\語法。 – Evert 2010-11-21 20:32:41