将 URI 的尾随数字替换为相应的 slug 文本
这是现有的 preg_match()
代码:
preg_match("/(\/)([0-9]+)(\/?)$/", $_SERVER["REQUEST_URI"], $m);
它很好地检测了以下 URI 字符串中的 post_id
:
http://www.example.com/health-and-fitness-tips/999/
我相信这应该是足够的背景了。
我将 999
(post_id
)更改为 how-do-I-lose-10kg-in-12-weeks',
post_title`,并且需要更改正则表达式来检测新字符串。
我的第一个想法是仅将 [az]\-
添加到正则表达式的末尾,从而生成以下正则表达式:
"/(\/)([0-9][a-z]/-+)(\/?)$/"
可能这么简单吗?如果不是的话,上面的内容有什么问题吗?
Here is the existing preg_match()
code:
preg_match("/(\/)([0-9]+)(\/?)$/", $_SERVER["REQUEST_URI"], $m);
It does a good job of detecting the post_id
in the following URI string:
http://www.example.com/health-and-fitness-tips/999/
I believe that should be enough background.
I'm changing the 999
(the post_id
) to how-do-I-lose-10kg-in-12-weeks', the
post_title`, and need to change the regex to detect the new string.
My first thought was to just add [a-z]\-
to the end of the regex making the following regex:
"/(\/)([0-9][a-z]/-+)(\/?)$/"
It is possibly this simple? If not, what is wrong with the above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不完全是:
([0-9][az]/-+)
是“一个数字,后跟一个字母,后跟至少一个破折号”。您需要
([-0-9a-z]+)
。Not quite:
([0-9][a-z]/-+)
is "a number, followed by a letter, followed by at least one dash."You want
([-0-9a-z]+)
.我只使用
\w
:来自 字符类或字符集:
I would just use
\w
:From Character Classes or Character Sets:
\w
代表单词,可以是大小写字母 A 到 Z 和 a 到 z,数字 0 到 9 或 _。它相当于[A-Za-z0-9_]
。您可以在此处的在线测试器中进行测试。\w
stands for word, can be letter both upper case and lower case A to Z and a to z, number 0 to 9 or _. It's equivalent to[A-Za-z0-9_]
. You can test in the online tester here.