Search code examples
phpregexescapingbackslash

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?


Solution

  • 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.