[英]php regex match word and stop
I have a URL like this http://website.com/clothes/men/type/t-shirts/color/red/size/xl...
and I need to perform an action when the url is like this http://website.com/clothes/(men or woman)/type/any-type
我有一个类似http://website.com/clothes/men/type/t-shirts/color/red/size/xl...
的URL,当URL像这样的http://website.com/clothes/(men or woman)/type/any-type
时,我需要执行一个操作http://website.com/clothes/(men or woman)/type/any-type
So if the after type/any-type
there are other values I don't want to perform the action. 因此,如果after type/any-type
还有其他值,则我不想执行该操作。
My regex looks like this right now preg_match('/clothes\\/(men|women)\\/type\\/(.*)\\/?$/', $_SERVER['REQUEST_URI'])
我的正则表达式现在看起来像这样preg_match('/clothes\\/(men|women)\\/type\\/(.*)\\/?$/', $_SERVER['REQUEST_URI'])
It matches the case I want, but it also matches if the URL continues after that specific key/value pair, so it also matches http://website.com/clothes/men/type/t-shirts/color/red
. 它与我想要的大小写匹配,但是如果URL在该特定键/值对之后继续,则也匹配,因此它也与http://website.com/clothes/men/type/t-shirts/color/red
匹配。
So in the end I need the preg_match()
to only match a URL that has only a type/anything
pair. 因此,最后我需要preg_match()
仅匹配仅具有type/anything
对的URL。
Thank you. 谢谢。
You can use: 您可以使用:
if ( preg_match('~/clothes/(?:wo)?men/type/[^/]+/$~i', $_SERVER['REQUEST_URI'], $m) ) {
// matches succeeds
}
~
to avoid escaping every forward slash 您可以使用类似~
分隔符来避免转义每个正斜杠 .*
in the end if you don't want to match after .../type/any-type/
如果您不想在.../type/any-type/
之后匹配,请最后删除.*
您可以只匹配[^/]+
:
preg_match('(clothes/(men|women)/type/([^/]+)/?$)', $_SERVER['REQUEST_URI'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.