【问题标题】:php preg_match() regular expressionphp preg_match() 正则表达式
【发布时间】:2015-02-24 11:00:26
【问题描述】:

我正在项目中进行 SEO 工作,以匹配可能 url 中的最佳 URL,所以 我正在尝试使用来自 url 模式的 preg_match() 函数匹配请求 url

谁能帮我创建正则表达式来匹配所有网址中的特定网址,我是正则表达式的新手,请看我的东西

以下 6 个网址,

1) http://domain.com/pressrelease
2) http://domain.com/pressrelease/
3) http://domain.com/pressrelease/index/1
4) http://domain.com/pressrelease/index/1/1/1
5) http://domain.com/pressrelease/inde2x/
6)http://domain.com/pressrelease/inde2x/2

我要匹配1,2,3 url,其他3个无效

我创建了这个正则表达式,但它不起作用

(\/pressrelease\/)+((?!index).)*$

【问题讨论】:

  • 您能解释一下为什么 4) 5) 6) 无效吗?什么是规则?
  • 我想匹配最好的 url,所以选择最好的 url,这不会很重要。

标签: php regex .htaccess


【解决方案1】:

我真的不明白你的要求的全部意义。

(@^http[s]?://[^/]/[^/]?(/?(index/[^/])?)?$@) p>

这将解决您的 1,2,3 而不是 4,5,6

https://regex101.com/r/fQ0hZ8/2

【讨论】:

  • 不需要匹配域和主机,反正工作正常
【解决方案2】:

这个正则表达式可能对你有用:

(/pressrelease)(/index/\d+)?/?$

RegEx Demo

【讨论】:

【解决方案3】:

这是 100% 的工作:

/(\/pressrelease)(\/)?((index))?(\/1)?$/m

https://regex101.com/r/kD9uD9/1

这里不是作弊的方法

【讨论】:

  • 小修改/(/pressrelease)(/)?((index))?(/\d+)?$/m 其他就好了
  • 刚刚在您的 URL 中工作,您没有说您希望被更改的内容但仍在工作。
【解决方案4】:

如果你想捕获整个字符串

(http:\/\/.*pressrelease(()|(\/)|(\/index)|(\/index\/[^\/]*)))$

https://regex101.com/r/aI0fB1/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2014-06-28
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多