php如何匹配反斜杠

from http://www.developwebsites.net/match-backslash-preg_match-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:


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

  • Finer points of PHP regular expressions
  • PHP Manual : preg_match

你可能感兴趣的:(php)