我想在我的404页面上匹配一个URL,并基于此我想将用户重定向到特定的位置。
URL为http://domain.com/there/12345
// example: /there/12345
$request = $_SERVER['REQUEST_URI'];
if (preg_match('', $request)) {
}
什么REGEX我应该把这个?一旦测试成功,我如何检索这个ID (12345),就在常数后面的?
您想使用的regexp是:
$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]+
也可以使用basename函数
$path = "http://domain.com/there/12345";
$filename = basename($path);
echo $filename; // Sholud be 12345
这应该可以满足您的需求:
$request = $_SERVER['REQUEST_URI'];
$match = array();
if (preg_match('@^/there/('d+)$@', $request, $match)) {
$id = $match[1];
// Do your processing here.
}
或者如果您倾向于忘记'd语法,并且希望避免@符号或/作为分隔符:
$request = '/there/12345';
if (preg_match('#/there/([0-9]+)#', $request, $match)) {
$id = $match[1];
echo "ID: $id";
}
可以的
if(preg_match('#^/there/('d+)$#', $request, $matches)){
echo "the id is {$matches[1]}";
}
else {
echo "no match!";
}
看它在这里工作
解释# delimiter
^ beginning of string
/there/ string literal '/there/'
( begin capture group 1
'd+ one or more [0-9]
) end capture group 1
$ end of string
# delimiter