PHP preg_replace

前端 未结 3 1616
余生分开走
余生分开走 2020-12-06 22:32

I use netbeans, I try to replace \\ with \\\\ but it fails , it can\'t escape the \\\\ character.

This is not a Netbeans issu

相关标签:
3条回答
  • 2020-12-06 23:09

    Try the php chr() function and tell the preg_replace the char ascii code for \ and \\.

    chr function

    ascii code table

    <?php
    echo chr(52) . "<br>"; // Decimal value
    echo chr(052) . "<br>"; // Octal value
    echo chr(0x52) . "<br>"; // Hex value
    
    preg_replace(chr(1),chr(2),'text'),
    
    ?>
    
    0 讨论(0)
  • 2020-12-06 23:09

    This works: (using str_replace() rather than preg_replace())

    $str = "text to \ be parsed";
    
    $str = str_replace('\\', '\\\\', $str);
    
    echo $str;
    
    0 讨论(0)
  • 2020-12-06 23:30

    Use 4 backslashes and please don't forget the delimiters:

    echo echo preg_replace('~\\\\~','\\\\\\\\','text to \\ be parsed');

    Online demo

    Explanation: When PHP parse \\\\ it will escape \\ two times, which means it becomes \\, now when PHP passes it to the regex engine, it will receive \\ which means \.

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