Somk
Somk

Reputation: 12047

Why does a single backslash and a double backslash perform the same escaping in regex?

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?

Upvotes: 7

Views: 1155

Answers (1)

Mathias-S
Mathias-S

Reputation: 805

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.

Upvotes: 5

Related Questions