使用php从URL字符串中捕获值

use*_*732 2 php parameters url capture

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

网址将如下所示:

index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44
Run Code Online (Sandbox Code Playgroud)

我怎样才能总是找到并捕获id的值,在这个例子中是2773?

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

谢谢

Jon*_*Jon 6

您正在寻找一个组合或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";
Run Code Online (Sandbox Code Playgroud)

看到它在行动.