通过添加 GET 参数来操作 url 字符串 [英] Manipulate a url string by adding GET parameters

查看:26
本文介绍了通过添加 GET 参数来操作 url 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不重复 ?& 的情况下向可能包含也可能不包含 GET 参数的 URL 添加 GET 参数.

I want to add GET parameters to URLs that may and may not contain GET parameters without repeating ? or &.

示例:

如果我想添加category=action

$url="http://www.acme.com";
 // will add ?category=action at the end

$url="http://www.acme.com/movies?sort=popular";
 // will add &category=action at the end

如果你注意到我试图不重复找到问号.

If you notice I'm trying to not repeat the question mark if it's found.

网址只是一个字符串.

附加特定 GET 参数的可靠方法是什么?

What is a reliable way to append a specific GET parameter?

推荐答案

基本方法

$query = parse_url($url, PHP_URL_QUERY);

// Returns a string if the URL has parameters or NULL if not
if ($query) {
    $url .= '&category=1';
} else {
    $url .= '?category=1';
}

更高级

$url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';

$url_parts = parse_url($url);
// If URL doesn't have a query string.
if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
    parse_str($url_parts['query'], $params);
} else {
    $params = array();
}

$params['category'] = 2;     // Overwrite if exists
$params['tags'][] = 'cool';  // Allows multiple values

// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);

// If you have pecl_http
echo http_build_url($url_parts);

// If not
echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];

你至少应该把它放在一个函数中,如果不是一个类.

You should put this in a function at least, if not a class.

这篇关于通过添加 GET 参数来操作 url 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆