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'

エスケープされた一重引用符 (2 番目の文のように) と二重のバックスラッシュ (3 番目の文のように) を使用して、表示されているとおりに 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'

可能であれば、コードにリストされているとおりに文字列をエコーし​​たいと思います。2 つのバックスラッシュ文字 (\) に問題があります。私の 2 番目のパターン ('~\\~') は、単一のバックスラッシュと二重のバックスラッシュの両方を置き換えているようです。同じ結果で 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 に答える