Extra backslash needed in PHP regexp pattern

后端 未结 4 1022
醉梦人生
醉梦人生 2020-11-28 13:22

When testing an answer for another user\'s question I found something I don\'t understand. The problem was to replace all literal \\t \\n \\r

4条回答
  •  离开以前
    2020-11-28 13:45

    You need 4 backslashes to represent 1 in regex because:

    • 2 backslashes are used for unescaping in a string ("\\\\" -> \\)
    • 1 backslash is used for unescaping in the regex engine (\\ -> \)

    From the PHP doc,

    escaping any other character will result in the backslash being printed too1

    Hence for \\\[,

    • 1 backslash is used for unescaping the \, one stay because \[ is invalid ("\\\[" -> \\[)
    • 1 backslash is used for unescaping in the regex engine (\\[ -> \[)

    Yes it works, but not a good practice.

提交回复
热议问题