I understand \s is used to match white space character, but sometimes I see "\\s" is used in preg match and working fine. For eg:
if (preg_match("/\\s/", $myString)) {
// there are spaces
}
if (preg_match("/\s/", $myString)) {
// there are spaces
}
Is there any difference between above two code blocks?
\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .
As far as I understand: \s means a whitespace character, \S Non-whitespace characters and [\S\s] means any character, anything.
means is "match any sequence of non-whitespace characters, including the empty string".
*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1 , eventually matching 101 . All quantifiers have a non-greedy mode: . *? , .
Trying to make sense of the text from the manual.
http://php.net/manual/en/regexp.reference.escape.php
Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.
I might not be correct but here I go.
When you use something like
preg_match("/\\s/", $myString)
What it is doing is converting \\ to \, which in turns make the string to be \s thus it behaves normally i.e its meaning doesn't change and the created regex is '/\s/' internally which matches "spaces"
To match \s in a string you would have to do something as follows
preg_match("/\\\\s/", $myString)
So the answer is \s or \\s in the regex string doesn't make any difference, personally I think using \s is simpler and easy to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With