How do you write a regular expression that will match \\test – two backslashes followed by some text in PHP? Well, obviously you’ll try something like this:

echo preg_match('/^\\([a-z]+)/', $word) ? 'match' : 'no match';

…but it won’t work. Furthermore, it will yield an error saying something like:

Compilation failed: unmatched parentheses at offset …

And it makes sense, since the backslash has a special meaning, as it’s the escape character, to give it a literal meaning you have to escape it. Like such:

echo preg_match('/^\\\\([a-z]+)/', $word) ? 'match' : 'no match';

…each of the two backslashes is escaped by another backslash placed in front of it. But this also doesn’t work :) The correct way to do it is:

echo preg_match('/^\\\\\\\\([a-z]+)/', $word) ? 'match' : 'no match';

Yeap. That’s right! With 8 backslashes. For each backslash you wanted matched, you need to add 4 in the regular expression. That’s because the backslash is considered to be an escape character by both PHP’s parser and its regexp engine. So, if you type a backslash in PHP, it’s considered and escape character by PHP’s parser.

If you write two backslashes in PHP, this construct will be interpreted as a literal backslash by PHP’s paser and sent to the regexp engine as an escape character. That’s right: ‘\\’ in PHP means a ‘\’ for the regexp engine. So, in order to pass a literal backslash to the regexp engine, you need to add 4 backslashes in PHP.

This is what I call backslash hell :(