[英]PHP preg_match Matching Wrong String
I have a regular expression: 我有一个正则表达式:
/\/(register)(?:\/activate\/(.{16}))?(?:\/(student|teacher|org))?\/?$/
Correct Matching Strings: 正确的匹配字符串:
/register
/register/student
/register/activate/1234567890123456/
Mismatch Problem: 不匹配问题:
/register/register/register/register/student/
The above still matches while using preg_match in PHP. 当在PHP中使用preg_match时,以上内容仍然匹配。 Any alternatives?
有其他选择吗?
I have also tried limiting 'register' to 1: 我也尝试将“寄存器”限制为1:
\/((?:register){1})(?:\/activate\/(.{16}))?(?:\/(student|teacher|org))?\/?$
No luck. 没运气。
It does not match using Debuggex, however it matched using http://www.phpliveregex.com/ 使用Debuggex不匹配,但是使用http://www.phpliveregex.com/匹配
Use a ^ at the beginning of your string to anchor it. 在字符串的开头使用^锚定。
/^\/(register)(?:\/activate\/(.{16}))?(?:\/(student|teacher|org))?\/?$/
* here
Without using anchor at beginning it is actually matching like below: 一开始不使用锚,实际上是如下所示的匹配:
/register/register/register/register/student/
^----------------^
The problem is you're only trying to match the end of the string by using $
. 问题是您只想使用
$
来匹配字符串的结尾。 This means the regex will match your expression, regardless of what comes before it. 这意味着正则表达式将匹配您的表达式,而不管它之前是什么。
Having an expression /bob$/
will match everything that ends with bob, eg big bob
. 具有表达式
/bob$/
将匹配以bob结尾的所有内容,例如big bob
。 That's exactly what's happening here. 这就是这里正在发生的事情。
You'll need to force preg_match
to match the entire string (ie both the beginning and the end) by prefixing it with ^
. 您需要通过为前缀加上
^
来强制preg_match
匹配整个字符串(即开头和结尾)。
/^\/(register)(?:\/activate\/(.{16}))?(?:\/(student|teacher|org))?\/?$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.