Why special characters like = or " break PHP regexp when using \b word boundary?

后端 未结 3 1536
臣服心动
臣服心动 2021-02-20 02:15

this is a follow up after reading How to specify "Space or end of string" and "space or start of string"?

From there, it states means to match a word

3条回答
  •  别那么骄傲
    2021-02-20 02:39

    The problem is your use of \b which is a "word boundary." It's a placeholder for (^\w|\w$|\W\w|\w\W), where \w is a "word" character [A-Za-z0-9_] and \W is the opposite. The problem is that a " doesn't match the "word" characters, so the boundary condition is not met.

    Try using a \s instead, which will match any whitespace character.

    (?:^|\s)stackoverflow=""(?:\s|$)
    

    Characters inside a class are not interpreted, except for ^ used as a negation operator at the beginning of a class, and - as a range operator. This is why [ ^] wouldn't work for you. It was searching for a literal ^.

    $ php -a
    Interactive shell
    
    php > $input_line='
    php ' stackoverflow="" xxx
    php ' xxx stackoverflow="" xxx
    php ' xxx stackoverflow=""
    php ' ';
    php > echo preg_replace('/(?:^|\s)stackoverflow=""(?:\s|$)/', 'OK', $input_line);
    OKxxx
    xxxOKxxx
    xxxOK
    

    https://regex101.com/r/nP2aB8/1

提交回复
热议问题