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.
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