PHP单引号字符串中的转义反斜杠字符 [英] Escaped Backslash Characters in PHP Single Quoted Strings

查看:390
本文介绍了PHP单引号字符串中的转义反斜杠字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从PHP手册中摘录了这些句子:

I took these sentences from the PHP manual:

'this is a simple string',
'Arnold once said: "I\'ll be back"',
'You deleted C:\\*.*?',
'You deleted C:\*.*?',
'This will not expand: \n a newline',
'Variables do not $expand $either'

我想使用PHP代码回显它们,就像它们看起来一样,带有转义的单引号(如第二句)和双反斜杠(如第三句).这是我到目前为止的内容:

I would like to echo them using PHP code, exactly as they appear, with escaped single quotes (like in the second sentence) and double backslashes (like in the third sentence). This is what I have so far:

<?php

$strings = array(
        'this is a simple string',
        'Arnold once said: "I\'ll be back"',
        'You deleted C:\\*.*?',
        'You deleted C:\*.*?',
        'This will not expand: \n a newline',
        'Variables do not $expand $either');

$patterns = array('~\\\'~', '~\\\\~');
$replacements = array('\\\\\'', '\\\\\\\\');

foreach($strings as $string)
{
        echo '\'' . preg_replace($patterns, $replacements, $string) . '\'' . '</br>';
}
?>

输出为:

'this is a simple string'
'Arnold once said: "I\\'ll be back"'
'You deleted C:\\*.*?'
'You deleted C:\\*.*?'
'This will not expand: \\n a newline'
'Variables do not $expand $either'

但是我想尽可能地回显我的代码中列出的字符串.我在使用双反斜杠字符(\)时遇到麻烦.我的第二个模式('〜\\〜')似乎替换了单反斜杠和双反斜杠.我还尝试过使用具有相同结果的addcslashes().

but I would like to echo the strings exactly as they are listed in my code if possible. I am having trouble with double backslash characters (\). My second pattern ('~\\~') seems to replace both single and double backslashes. I also tried using addcslashes() with the same results.

(我最近在其他地方问过这个问题,但没有解决方案)

(I have asked this question elsewhere recently but without a solution)

谢谢.

推荐答案

考虑使用var_export()来打印字符串的真实副本",而不是干预preg_replace():

Instead of meddling with preg_replace(), consider using var_export() to print a "true copy" of the string:

foreach ($strings as $s) {
    echo var_export($s, true), PHP_EOL;
}

输出:

'this is a simple string'
'Arnold once said: "I\'ll be back"'
'You deleted C:\\*.*?'
'You deleted C:\\*.*?'
'This will not expand: \\n a newline'
'Variables do not $expand $either'

如您所见,句子3和4与PHP相同.

As you can see, sentence 3 and 4 are identical to PHP.

这篇关于PHP单引号字符串中的转义反斜杠字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆