PHP Regex: difference between \ s and \\ s

I understand that \ s is used to match the space character, but sometimes I see "\\ s" being used in a preliminary match and works fine. For instance,

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

Is there a difference between the two above blocks of code?

+5
source share
2 answers

Trying to understand the text from the manual.

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

Separate and double quotes of PHP strings are especially important for backslashes. Thus, if \ should be matched with the regular expression \\, then "\\\\" or '\\\\' should be used in the PHP code.

Maybe I'm wrong, but here I go.

When you use something like

 preg_match("/\\s/", $myString) 

What he does is convert \\ to \, which in turn makes the string equal to \ s, so it behaves normally, that is, its value does not change, and the created regular expression '/ \ s /' internally matches " space "

To match \ s in a string, you need to do something like this

 preg_match("/\\\\s/", $myString) 

So, the answer: \ s or \\ s in the regex string does not matter, personally I think that using \ s is simpler and easier to understand.

+4
source
 \s - to match all white spaces \\s - to match all white spaces \\\s - to match all \s 
0
source

Source: https://habr.com/ru/post/1242267/


All Articles