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

时间:2012-06-06 17:13:28

标签: php

我从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(),结果相同。

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

提前致谢。

2 个答案:

答案 0 :(得分:2)

请考虑使用preg_replace()打印字符串的“真实副本”,而不是干涉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相同。

答案 1 :(得分:1)

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

 <?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 这是DEMO