繁体   English   中英

PHP单引号字符串中的转义反斜杠字符

[英]Escaped Backslash Characters in PHP Single Quoted Strings

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

'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代码回显它们,就像它们看起来一样,使用转义的单引号(如第二句)和双反斜杠(如第三句)。 这是我到目前为止的内容:

<?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()。

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

提前致谢。

与其干预preg_replace()var_export()考虑使用var_export()打印字符串的“真实副本”:

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相同。

试试这个代码。 它按预期工作。

 <?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){
    print_r(strip_tags($string,"\n,:/"));
    print_r("\n");
 }
?>

您可以在strip_tags中指定allowable_tags。 请参考strip_tags以进一步了解这是演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM