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
echo preg_match('/^\\\\{2}([a-z]+)/', $word) ? 'match' : 'no match';but it’s still ugly.
Yeah, anyway, the point is that one should add 4 backslashes in code for every backslash you want matched…
And, personally, when I want to match 2 characters, like aa, I usually write /aa/ instead of /a{2}/. That’s how I roll
In .NET, the solution is to use a special string syntax that accepts any character, including new lines, and that only escapes quotes with double quote characters. Instead of “\\t” use @”\t” which is perfect for Regex and things like embedded scripts that contain newlines and would be ugly with \r\n in them. As far as I remember there is no alternative syntax for strings in PHP, but it sure seems like a useful construct to me.
Hi,
I want to replace three backslashes with null character.
But using 12 backslashes , it is not working
Example :
1. \\\ replace with null
2. \\\\ replace with \
Try it like this:
$string = $_GET['string']; $regexp = '/(\\\\){3}/'; echo $string . PHP_EOL; echo preg_replace($regexp, '', $string) . PHP_EOL;