通过添加GET参数来操作url字符串

Rya*_*yan 74 php string url

我想将GET参数添加到可能包含但不包含GET参数的URL而不重复?&.

例:

如果我想添加 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
Run Code Online (Sandbox Code Playgroud)

如果您发现我试图不重复问号,如果找到了.

URL只是一个字符串.

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

and*_*ber 162

基本方法

$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';
}
Run Code Online (Sandbox Code Playgroud)

更先进

$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'];
Run Code Online (Sandbox Code Playgroud)

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

  • 为parse_url +1,已经忘记了! (4认同)
  • @DougT.并非所有参数都需要一个值.例如,可以使用`isset($ _ GET ["logout"])`来检查`?logout` (3认同)
  • 也不要忘记追加类别的价值 (2认同)

ryb*_*111 44

这是接受答案的缩写版本:

$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . 'category=action';
Run Code Online (Sandbox Code Playgroud)

编辑:正如在接受的答案中所讨论的,这是有缺陷的,因为它不会检查是否category已经存在.一个更好的解决方案是对待$_GET它是什么 - 一个数组 - 并使用像这样的函数in_array().

  • 不处理带有 `#` 的 URL。 (2认同)

Tom*_*aus 18

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

$queryString =  http_build_query($data);
//$queryString = foo=bar&baz=boom&cow=milk&php=hypertext+processor

echo 'http://domain.com?'.$queryString;
//output: http://domain.com?foo=bar&baz=boom&cow=milk&php=hypertext+processor
Run Code Online (Sandbox Code Playgroud)


Dou*_* T. 9

使用strpos来检测?既然?只能出现在查询字符串开头的URL中,你知道它是否已经存在params并且你需要使用&添加params

function addGetParamToUrl(&$url, $varName, $value)
{
    // is there already an ?
    if (strpos($url, "?"))
    {
        $url .= "&" . $varName . "=" . $value; 
    }
    else
    {
        $url .= "?" . $varName . "=" . $value;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

此函数会覆盖现有参数

function addToURL( $key, $value, $url) {
    $info = parse_url( $url );
    parse_str( $info['query'], $query );
    return $info['scheme'] . '://' . $info['host'] . $info['path'] . '?' . http_build_query( $query ? array_merge( $query, array($key => $value ) ) : array( $key => $value ) );
}
Run Code Online (Sandbox Code Playgroud)


Арт*_*цын 7

更新现有参数的示例.

还使用url_encode,并且可能不指定参数值

    <?
    /**
     * Add parameter to URL
     * @param string $url
     * @param string $key
     * @param string $value
     * @return string result URL
     */
    function addToUrl($url, $key, $value = null) {
        $query = parse_url($url, PHP_URL_QUERY);
        if ($query) {
            parse_str($query, $queryParams);
            $queryParams[$key] = $value;
            $url = str_replace("?$query", '?' . http_build_query($queryParams), $url);
        } else {
            $url .= '?' . urlencode($key) . '=' . urlencode($value);
        }
        return $url;
    }
Run Code Online (Sandbox Code Playgroud)


the*_*uts 7

单线:

$url .= (strpos($url, '?') ? '&' : '?') . http_build_query($additionalParams);
Run Code Online (Sandbox Code Playgroud)

建议使用http_build_query,因为它对特殊字符进行编码(例如空格或@电子邮件地址)


2022 年改进版本

这允许替换现有参数,并且还保留现有 URL 片段(#URL 末尾之后的部分)

function addParametersToUrl(string $url, array $newParams): string
{
    $url = parse_url($url);
    parse_str($url['query'] ?? '', $existingParams);

    $newQuery = array_merge($existingParams, $newParams);

    $newUrl = $url['scheme'] . '://' . $url['host'] . ($url['path'] ?? '');
    if ($newQuery) {
        $newUrl .= '?' . http_build_query($newQuery);
    }

    if (isset($url['fragment'])) {
        $newUrl .= '#' . $url['fragment'];
    }

    return $newUrl;
}
Run Code Online (Sandbox Code Playgroud)

测试:

$newParams = [
    'newKey' => 'newValue',
    'existingKey' => 'new',
];

echo addParametersToUrl('https://www.example.com', $newParams);
// https://www.example.com?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/', $newParams);
// https://www.example.com/dir/?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/', $newParams);
// https://www.example.com/dir/?newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar', $newParams);
// https://www.example.com/dir/file?foo=bar&newKey=newValue&existingKey=new
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar&existingKey=old', $newParams);
// https://www.example.com/dir/file?foo=bar&existingKey=new&newKey=newValue
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar&existingKey=old#hash', $newParams);
// https://www.example.com/dir/file?foo=bar&existingKey=new&newKey=newValue#hash
echo addParametersToUrl('https://www.example.com/dir/file#hash', $newParams);
// https://www.example.com/dir/file?newKey=newValue&existingKey=new#hash
echo addParametersToUrl('https://www.example.com/dir/file?foo=bar#hash', $newParams);
// https://www.example.com/dir/file?foo=bar&newKey=newValue&existingKey=new#hash
Run Code Online (Sandbox Code Playgroud)


Lon*_*ren 5

 /**
 * @example addParamToUrl('/path/to/?find=1', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
 * @example addParamToUrl('//example.com/path/to/?find=1', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
 * @example addParamToUrl('https://example.com/path/to/?find=1&FILTER=Y', array('find' => array('search', 2), 'FILTER' => 'STATUS'))
 *
 * @param       $url string url
 * @param array $addParams
 *
 * @return string
 */
function addParamToUrl($url, array $addParams) {
  if (!is_array($addParams)) {
    return $url;
  }

  $info = parse_url($url);

  $query = array();

  if ($info['query']) {
    parse_str($info['query'], $query);
  }

  if (!is_array($query)) {
    $query = array();
  }

  $params = array_merge($query, $addParams);

  $result = '';

  if ($info['scheme']) {
    $result .= $info['scheme'] . ':';
  }

  if ($info['host']) {
    $result .= '//' . $info['host'];
  }

  if ($info['path']) {
    $result .= $info['path'];
  }

  if ($params) {
    $result .= '?' . http_build_query($params);
  }

  return $result;
}
Run Code Online (Sandbox Code Playgroud)


she*_*_xu 5

<?php
$url1 = '/test?a=4&b=3';
$url2 = 'www.baidu.com/test?a=4&b=3&try_count=1';
$url3 = 'http://www.baidu.com/test?a=4&b=3&try_count=2';
$url4 = '/test';
function add_or_update_params($url,$key,$value){
    $a = parse_url($url);
    $query = $a['query'] ? $a['query'] : '';
    parse_str($query,$params);
    $params[$key] = $value;
    $query = http_build_query($params);
    $result = '';
    if($a['scheme']){
        $result .= $a['scheme'] . ':';
    }
    if($a['host']){
        $result .= '//' . $a['host'];
    }
    if($a['path']){
        $result .=  $a['path'];
    }
    if($query){
        $result .=  '?' . $query;
    }
    return $result;
}
echo add_or_update_params($url1,'try_count',1);
echo "\n";
echo add_or_update_params($url2,'try_count',2);
echo "\n";
echo add_or_update_params($url3,'try_count',3);
echo "\n";
echo add_or_update_params($url4,'try_count',4);
echo "\n";
Run Code Online (Sandbox Code Playgroud)

  • 很棒的工作,只替换行 ``$query = $a['query'] 吗?$a['query'] : '';`` by ``$query =isset($a['query']) ? $a['query'] : '';`` (3认同)