How to Match A Backslash with preg_match() in PHP

What is preg_match()?

The preg_match() function will perform a Perl-compatible regular expression pattern match. Sometimes you will want to match a backslash, but it’s not as straightforward as you might first think!

In a regular expression a backslash(“\”) is used to escape a special characters so that they will be interpreted literally in the pattern.

For example, the full stop character (“.”) has a special meaning – it means “any character”. Therefore if you want to match a literal full stop you must escape it with a backslash, for example (“\.”).

Match a Backslash

Since a backslash is used to escape the following character and have it treated literally, you might assume that you would escape the backslash itself with another backslash (e.g. “\\”).

Congratulations – you’re on the right track! That’s how you might expect to match a backslash, by escaping it with another backslash. Unfortunately it’s not quite that simple!

The Backslash Solution

To match a literal backslash using PHP’s preg_match() function you must use 4 backslashes:

<?php
preg_match('/\\\\/', $subject);
?>

Why 4 Backslashes?

Yes, it seems crazy to have to use 4 backslashes just to match one literal backslash! It must be done like this because every backslash in a C-like string must be escaped by a backslash. That would give us a regular expression with 2 backslashes, as you might have assumed at first. However, each backslash in a regular expression must be escaped by a backslash, too. This is the reason that we end up with 4 backslashes.

Another Solution

A literal backslash can also be matched using preg_match() by using a character class instead. Backslashes are not escaped when they appear within character classes in regular expressions. Therefore (“[\\]”) would match a literal backslash. The backslash must still be escaped once by another backslash because it is still a C-like string.

Conclusion

If you’ve been trying without success to match a backslash using PHP’s preg_match() function I hope that this has cleared things up for you! This will also work for other functions that use Perl-compatible regular expressions, such as preg_replace().

Useful Resources

14 Comments

  1. Noor

    preg_match(‘/\\\\/’, $somedatawithbackslash);
    throws exception: Warning: preg_match() [function.preg-match]: No ending matching delimiter \’]\’ found

  2. Barnaby Knowles

    That’s strange – I can’t replicate the error.

    I’d hazard a guess that the final backslash is escaping the forward slash that completes the regular expression.

  3. Shawn

    Actually you would only use three slashes to represent a literal slash: ‘/\\\/’

  4. Alex

    why is nobody telling him he is not matchin a backslash ! its a slash /=backslash \=slash! you killing my google search 4 how too match the real backslash! thx

  5. Barnaby Knowles

    Hi Alex.

    You’ve got it the wrong way around. A “/” is a forward slash, whilst a “\” is a backslash.

  6. pascal

    Alex that was funny. Thanks for the post Barnaby

  7. Amanjot Singh

    thanks, its working. the php preg_match function stops escaping after 4 back slashes.

  8. Ravi Kanojiya

    please let me know how to check the forward slash at the beginning of line, same as php comment

  9. Barnaby Knowles

    Hi Ravi,

    You can use a different pattern delimiter, such as a hash, instead of a forward slash, and then just match the forward slash like any other character:

    preg_match('#^/#', $subject);
  10. Johnathan

    You just need to remember to duplicate the number of backslash you need. For example if you need to match 2 backslashes(\) then you need 4 backslashes(\\) or just \{2}.

    Here’s demo example using live regex tester
    http://liveregex.com/xoJdk

  11. Jake

    I believe that this is the answer to why 3 backslashes often works as well as 4, in the PHP manual for strings, under ‘double quoted strings’:
    “As in single quoted strings, escaping any other character will result in the backslash being printed too.”
    http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double

    So as long as a backslash combined with the next character does not have any meta meaning, a single backslash prints as a single backslash.
    So “\\a” outputs as \a (like we already knew)
    And “\a” also outputs as \a (since \a has no special meaning)
    And “\\\a” ouputs as \\a, which regex then sees as literal \a

  12. Panji PRASETYO

    Hai Barnaby Knowles,

    Thank You, it works.

    Regards,
    Panji.

  13. cito

    Read about single and double quoted strings and escaping: http://php.net/manual/en/language.types.string.php https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php

    Probably best to always var_dump your pattern if unsure to see how many backslashes are actually passed to the regex parser. It should be two because the backslash needs to be escaped for the regex parser as well for being matched literally as it’s an escape in regex as well.

    For most cases in single quoted patterns 3 backslashes would suffice to match a backslash literally, in double quoted patterns 4.

Leave a Reply

Your email address will not be published. Required fields are marked *