我想匹配我的 404 页面上的 URL,并基于此我想将用户重定向到特定位置。
网址是http://domain.com/there/12345
// example: /there/12345
$request = $_SERVER['REQUEST_URI'];
if (preg_match('', $request)) {
}
我应该输入什么 REGEX 才能得到这个?一旦测试成功,如何在常量 there 之后立即检索此 ID (12345)?
最佳答案
您要使用的正则表达式是:
$str=$_SERVER['REQUEST_URI'];
$regex = '/\/there\/(\d+)/';
$matches=array();
preg_match($regex, $str, $matches);
var_dump($matches)
这给出了
array
0 => string '/there/12345' (length=12)
1 => string '12345' (length=5)
注意 \d+
周围的括号捕获任何 \d+
匹配的内容(即连续的数字 0-9 字符串)
如果你想要一个十六进制的 id(比如 12ABF),那么你应该将 \d+
更改为 [a-zA-Z\d]+
关于PHP URL 正则表达式和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8375032/