php 根据系统斜杠,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值