我理解 \s 用于匹配空格字符,但有时我会看到在 preg_match 中使用 "\\s" 并且能够正常工作。例如:
if (preg_match("/\\s/", $myString)) {
// there are spaces
}
if (preg_match("/\s/", $myString)) {
// there are spaces
}
上述两个代码块有什么区别吗?
试着理解手册中的文字。
http://php.net/manual/en/regexp.reference.escape.php
在单引号和双引号的 PHP 字符串中,反斜杠有特殊含义。 如果需要将反斜杠 \ 与正则表达式匹配,则必须在 PHP 代码中使用 "\\\\" 或 '\\\\'。
我可能不是正确的,但我尝试一下。
当你使用类似于
preg_match("/\\s/", $myString)
preg_match("/\\\\s/", $myString)
因此,在正则表达式字符串中,\s或\\s的答案没有任何区别。个人认为使用\s更简单易懂。
\n
表示LF等)。您不能在文字中声明它们(原义字符串文字,术语可能不同)。在PHP中,即使在双引号和单引号字符串文字中\b
仍然是一个单词边界,我亲自测试过,感到非常惊讶。请注意,在JS、Java、Python中,正常字符串文字中的\b
是退格字符。因此,在PHP中的歧义是由引擎本身解决的。 - Wiktor Stribiżew\s - to match all white spaces
\\s - to match all white spaces
\\\s - to match all \s
("/\s/", "hello hi") = 1
时,输出是正确的,因为只有一个空格。第一个表达式将尝试在字符串中匹配\s
。可以在 https://regex101.com/ 进行尝试。 - rock321987r"\\s"
的东西,可以用来显示结果的差异...不过我不知道PHP是否也有这个。 - rock321987