0

我从 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()。

(我最近在别处问过这个问题,但没有解决方案)

提前致谢。

4

2 回答 2

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

于 2012-06-07T09:53:27.117 回答
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

于 2012-06-06T17:38:28.063 回答