反斜杠转义字符串的解码器
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
stripcslashes()
几乎有效,只是它不会' t 识别 \a 并跳过它:(输出这个...
stripcslashes()
almost works, except that it won't recognize \a and skips it :(outputs this...