Escaped Backslash Characters in PHP Single Quoted Strings

前端 未结 2 2045
暗喜
暗喜 2020-12-22 10:34

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         


        
相关标签:
2条回答
  • 2020-12-22 11:19

    Try this code. It is working as expected.

     <?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");
     }
    ?>
    

    You can specify allowable_tags in strip_tags. Refer strip_tags for further understanding Here is DEMO

    0 讨论(0)
  • 2020-12-22 11:21

    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;
    }
    

    Output:

    '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'
    

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

    0 讨论(0)
提交回复
热议问题