Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex: Difference between \s and \\s

Tags:

regex

php

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?

like image 284
joHN Avatar asked Feb 04 '16 04:02

joHN


People also ask

What does \\ mean in regex?

\\. 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?\ ' .

What is \S and \s in regex?

As far as I understand: \s means a whitespace character, \S Non-whitespace characters and [\S\s] means any character, anything.

What does S * mean in regex?

means is "match any sequence of non-whitespace characters, including the empty string".

What is the difference between * and *??

*? 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: . *? , .


1 Answers

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.

like image 50
codisfy Avatar answered Oct 29 '22 18:10

codisfy