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

发布于 2024-12-19 05:07:33 字数 349 浏览 3 评论 0原文

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

网址将如下所示:

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

How can I always find &捕获 id 的值(在本例中为 2773)?

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

谢谢

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.

The url's will look like:

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

How can I always find & capture the value of the id which in this example is 2773?

I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦幻之岛 2024-12-26 05:07:33

您正在寻找组合或 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";

查看实际操作

You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).

For example:

$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";

See it in action.

一杯敬自由 2024-12-26 05:07:33

您可以使用 parse_str

You can use parse_str

陪我终i 2024-12-26 05:07:33

你可以使用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;

You can use parse_url to parse URLs!

But you can use, to extract directly the numbers of ID variable:

$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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文