开发者

Strange Unaccepted PHP Regex Pattern

So, in the process of trying to bug fix an unexpected error, I have come to the conclusion that the follo开发者_如何学运维wing is somehow unacceptable in php:

$pattern = "/\/sc2\/en\/profile\/693604\/1\/EGIdrA\/ladder\/";
$subject = "\/sc2\/en\/profile\/693604\/1\/EGIdrA\/ladder\/";
preg_match($pattern, $subject, $result);

I have no idea how or why - all I know is that if I have this line, then various debugging echoes of various words at various locations both before and after this line are no longer echoed. There are no loops anywhere, so I am quite confused as to why this is causing a problem.


There is no need to escape slashes in strings. '\/' is the same as '\\/', i.e. the string \/.

In regular expressions, \/ escapes a slash if you're using slashes to terminate the expression. You don't need that, simply choose another terminator, like #:

preg_match('#^/sc2/en/profile/693604/1/EGIdrA/ladder/$#',
           '/sc2/en/profile/693604/1/EGIdrA/ladder/', $result);

A single call to preg_match does not halt execution of a program. However, a variety of errors and warnings can be emitted - for example, you're missing a terminating / in the regular expression which yields

PHP Warning:  preg_match(): No ending delimiter '/' found

Check your server's php settings (namely error_reporting and log_errors) for warning and error output configuration. On many systems, /var/log/apache*/error.log contains all php errors and warnings. Note that a set display_errors can modify the output and make it an invalid XML document or confuse advanced output buffering.


Here's why:

preg_match('/^\/$/', '\/'); // false
preg_match('/^\/$/', '/'); // true


You should not escape slashes / in input string, it's enough to escape them in pattern

preg_match('/^\/sc2\/en\/profile\/693604\/1\/EGIdrA\/ladder\/$/',
       '/sc2/en/profile/693604/1/EGIdrA/ladder/', $result);

(or like phihag mentioned, use i.e. # for pattern termination)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜