PHP正则表达式:\ s和\\ s之间的区别

joH*_*oHN 5 php regex

我理解\ s用于匹配空格字符,但有时我看到"\\ s"用于preg匹配并且工作正常.例如:

if (preg_match("/\\s/", $myString)) {
   // there are spaces
}

if (preg_match("/\s/", $myString)) {
   // there are spaces
}
Run Code Online (Sandbox Code Playgroud)

上面两个代码块之间有什么区别吗?

cod*_*sfy 4

尝试理解手册中的文字。

http://php.net/manual/en/regexp.reference.escape.php

单引号和双引号 PHP 字符串具有反斜杠的特殊含义。因此,如果 \ 必须与正则表达式 \\ 匹配,则必须在 PHP 代码中使用“\\\\”或 '\\\\'。

我可能不正确,但我走了。

当你使用类似的东西时

preg_match("/\\s/", $myString)
Run Code Online (Sandbox Code Playgroud)

它所做的是将 \\ 转换为 \,这又使字符串成为 \s,因此它的行为正常,即它的含义不会改变,并且创建的正则表达式在内部是 '/\s/' 匹配“空格”

要匹配字符串中的 \s,您必须执行以下操作

preg_match("/\\\\s/", $myString)
Run Code Online (Sandbox Code Playgroud)

所以答案是正则表达式字符串中的 \s 或 \\s 没有任何区别,我个人认为使用 \s 更简单且易于理解。