将查询字符串添加到随机 URL [英] Adding a query string to a random URL

查看:67
本文介绍了将查询字符串添加到随机 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 URL 添加查询字符串,但是 URL 格式无法预测.网址可以是

I want to add a query string to a URL, however, the URL format is unpredictable. The URL can be

  • http://example.com/page/ -> http://example.com/page/?myquery=string
  • http://example.com/page -> http://example.com/page?myquery=string
  • http://example.com?p=page -> http://example.com?p=page&myquery=string
  • http://example.com/page/ -> http://example.com/page/?myquery=string
  • http://example.com/page -> http://example.com/page?myquery=string
  • http://example.com?p=page -> http://example.com?p=page&myquery=string

这些是我想到的网址,但可能还有其他格式我不知道.

These are the URLs I'm thinking of, but it's possible that there are other formats that I'm not aware of.

我想知道是否有标准、库或通用方法可以做到这一点.我正在使用 PHP.

I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.

我正在使用 Cbroe 解释和 路人 代码.Hamza 还有另一个 函数,但我想最好使用 PHP 函数并且代码更简洁/更短.

I'm using Cbroe explanation and Passerby code. There is another function by Hamza but I guess it'd be better to use PHP functions and also have cleaner/shorter code.

推荐答案

function addQuery($url,array $query)
{
    $cache=parse_url($url,PHP_URL_QUERY);
    if(empty($cache)) return $url."?".http_build_query($query);
    else return $url."&".http_build_query($query);
}

// test
$test=array("http://example.com/page/","http://example.com/page","http://example.com/?p=page");
print_r(array_map(function($v){
    return addQuery($v,array("myquery"=>"string"));
},$test));

现场演示

这篇关于将查询字符串添加到随机 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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