使用PHP和正则表达式的自定义URL路由 [英] Custom URL routing with PHP and regex
问题描述
我正在尝试创建一个非常简单的URL路由,我的思考过程是这样的:
I'm trying to create a very simple URL routing, and my thought process was this:
- 首先检查所有静态URL
- 然后检查数据库URL
- 然后返回404(如果不存在)
静态URL当然很容易实现,但是我正在尝试找出动态URL的最佳方法.我希望不必设置静态前缀,尽管知道这样做会使编写代码变得容易得多.
The static URLs are easy to do of course, but I'm trying to figure out the best way to do dynamic ones. I would prefer not to have to set a static prefix, despite knowing that it would make this a lot easier to code.
这是我目前拥有的:
$requestURL = $_SERVER['REQUEST_URI'];
if ($requestURL == '/') {
// do stuff for the homepage
}
elseif ($requestURL == '/register') {
// do stuff for registration
}
// should match just "/some-unique-url-here"
elseif (preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) {
// query database for that url variable
}
// should match "/some-unique-url/and-another-unique-url"
elseif (preg_match("(^\/[A-Za-z0-9\-]+\/[A-Za-z0-9\-]+)/",$requestURL)) {
// query database for first and second variable
}
else {
// 404 stuff
}
我的问题是,如果我具有"/register" URI,它将与第二个elseif语句以及regex语句匹配.但我想避免不得不从正则表达式中专门排除每个静态URL,例如:
My problem is that if I have "/register" URI, it will match the second elseif statement as well as the regex statement. But I want to avoid having to specifically exclude each static URL from regex statement, such as this:
// should match just "/some-unique-url-here"
elseif ((preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) &&
($requestURL !== '/register') &&
($requestURL !== '/')) {
// query database for that url variable
}
解决此问题的最简单方法是什么?我可能会喜欢15-20个静态URL,因此专门排除所有这些URL将非常笨拙.
What's the easiest way to solve this problem? I'll probably have like 15-20 static URLs, so specifically excluding all of them would be very clunky.
推荐答案
您的问题不存在.如果第一个elseif ($requestURL == '/register')
匹配,则同一级别上的所有后续elseif
都不会得到评估.
Your problem does not exist. If the first elseif ($requestURL == '/register')
matches, all subsequent elseif
s on the same level won't get evaluated.
您已经做对了,只需确保首先进行字符串比较(==
).
You're already doing it right, just make sure you do the string comparisons (==
) first.
另一方面,请不要重新发明轮子.
On another note, don't reinvent the wheel.
- https://github.com/bramus/router
- http://toroweb.org/
- http://zaphpa.org/
这篇关于使用PHP和正则表达式的自定义URL路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!