我正在尝试检测可能存在 get params 等的 URI。我只需要获取/val1/val2,无论是否有任何 url get params 等。我如何在 php 中执行此操作?
谢谢
$regex = '/^\/index.php?(.*)?\?+$/';
// Here are some example URLS
site.com/val1/val2
site.com/index.php/val1/val2
site.com/index.php/val1/val2?get1=val1&get2=val2
我希望能够对 (/val1/val2) 进行分组,无论 uri 左侧或右侧是什么
最佳答案
您可以使用
(?:/[^/?#]+){2}(?=[?#]|$)
请参阅regex demo
详细信息
-
(?:/[^/?#]+){2}
- 两次重复/
然后是/
之外的 1+ 个字符,?
和#
-
(?=[?#]|$)
- 与紧随?
的位置匹配的正向前瞻,#
或字符串结尾。
这是regex graph :
PHP code :
$re = '~(?:/[^/?#]+){2}(?=[?#]|$)~';
$str = 'site.com/val1/val2';
if (preg_match($re, $str, $match)) {
print_r($match[0]);
} // => /val1/val2
关于用于检测 Url URI 的 PHP 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901446/