如何使用请求 URL 提取值


How to extract value using request url

我的$_SERVER['REQUEST_URI']类似于/advt/upload/siteid/1。我需要从指定的路径中检索"1"。我怎样才能做怀孕匹配或其他任何事情?

谢谢!

你想要最后一个路径段?容易!

$lastPathSegment = basename($_SERVER['REQUEST_URI']);

代码板。

您可能希望使用 rtrim($_SERVER['REQUEST_URI'], '/') 来确保路径没有尾部斜杠。

还有许多其他方法可以做到这一点。假设$uri = rtrim($_SERVER['REQUEST_URI'], '/')...

$lastPathSegment = end(explode("/", $uri));

代码板。

$lastPathSegment = ltrim(strrchr($uri, "/"), "/"); 

代码板。

$lastPathSegment = substr($uri, 1 + strrpos($uri, "/"));

代码板。

$lastPathSegment = preg_replace('/^.+'//', '', $uri);

代码板。

。等等。

如果你想要最后一个段:

$endSegment = basename($_SERVER['REQUEST_URI']);

否则,如果它不是最后一个,但你知道值的索引

$pieces = explode("/", $_SERVER['REQUEST_URI']);
$selectedSegment = $pieces[3];

您可以使用拆分函数,即

list($sec1,$sect2,$sect3,$sect4) = explode("/", $_SERVER['REQUEST_URI']);

其中 $sect 4 是你的数字,或者只是一个直线数组

$uri = explode("/", $_SERVER['REQUEST_URI']);
$num = $uri[3];

您可能还想查看正则表达式

preg_match('/(?P<sect1>'w+)'(?P<sec2>'w+)'(?P<sect3>'w+)' (?P<digit>'d+)/', $_SERVER['REQUEST_URI'], $matches);
print_r($matches);

有关预产preg_match比赛的更多信息,请参阅此链接