用php从URL字符串获取值


Capture value from URL string with php

我需要从字符串中提取变量的值,这恰好是一个URL。字符串/url是作为单独的php查询的一部分加载的,而不是浏览器中的url。

url看起来像:

index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44

我怎么总能找到&捕获id的值(在本例中为2773?)

我已经读了几个例子,但我所尝试的是捕获正在浏览器中查看的当前页面的id值,而不是URL字符串。

谢谢

您正在寻找parse_url(将为您隔离查询字符串)和parse_str(将解析变量并将它们放入数组)的组合。

例如:

$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
print_r($vars); // see what's in there
// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));
// This will also work:
$id = intval($vars['id']);
echo "The id is $id'n";

查看效果

可以使用parse_str

您可以使用parse_url来解析url !

但是你可以使用,来直接提取ID变量的个数:

$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;