Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preg match forward slashes

I am trying to match 008/

preg_match('/008\\//i', '008/', $matches);
preg_match('/008\//i', '008/', $matches);

My question is why do both of the regular expressions work. I would expect the second to work, but why does the double backslash one work?

like image 827
Somk Avatar asked Nov 25 '15 23:11

Somk


People also ask

What does preg_ match return?

The preg_match() function returns whether a match was found in a string.

Is preg match case insensitive?

preg_match is case sensitive. A match. Add the letter "i" to the end of the pattern string to perform a case-insensitive match.


1 Answers

Because \\ in PHP strings means "escape the backslash". Since \/ doesn't mean anything it doesn't need to be escaped (even though it's possible), so they evaluate to the same.

In other words, both of these will print the same thing:

echo '/008\\//i'; // prints /008\//i
echo '/008\//i';  // prints /008\//i

The backslash is one of the few characters that can get escaped in a single quoted string (aside from the obvious \'), which ensures that you can make a string such as 'test\\' without escaping last quote.

like image 136
Mathias-S Avatar answered Oct 18 '22 20:10

Mathias-S