繁体   English   中英

RegExp以匹配URL的一部分

[英]RegExp to match a segment of a URL

我正在尝试使用RegExp来匹配URL的一部分。

有问题的网址是这样的:

http://www.example.com/news/region/north-america/

由于我需要WordPress URL Rewrite API的此正则表达式,因此主题只会是URL的path部分:

news/region/north-america

在上面的示例中,我需要能够提取路径的北美部分,但是当使用分页时,路径变为如下所示:

news/region/north-america/page/2

我仍然只需要提取北美部分。

我想出的RegExp如下:

^news/region/(.*?)/(.*?)?/?(.*?)?$

但是,这仅与news/region/north-america/page/2 news/region/north-america不匹配

据我所知,我需要将north-america后的斜杠设为可选,但要添加/? 似乎不起作用。

尝试这个:

preg_match('/news\/region\/(.*?)\//',"http://www.example.com/news/region/north-america/page/2",$matches);

$ matches [1]将为您提供输出。 作为“北美”。

您应该使用此正则表达式进行匹配:

^news/region/([^/]+)

即使URI变为/news/region/north-america/page/2这也将为您提供news/region/north-america

georg建议的规则运作就像一种魅力:

^news/region/(.*?)(?:/(.*?)/(.*?))?$

对于那些对此正则表达式的应用感兴趣的人,我在WP Rewrite API中使用了它来获取自定义分类法和页码(如果存在),并将相关的匹配项分配给WP Rewrite:

$ newRules [ '消息/区域/(?)(?:??/()/(*))?$'] ='的index.php区域= $匹配[1]&forcetemplate =新闻和寻呼= $匹配[3]';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM