php 更好的方法来替换给定URL中的查询字符串值

tnkciper  于 2023-04-04  发布在  PHP
关注(0)|答案(9)|浏览(125)

好吧,基本上,假设我们有一个链接:

$url = "http://www.site.com/index.php?sub=Mawson&state=QLD&cat=4&page=2&sort=z";

基本上,我需要创建一个函数,它替换URL中的每个内容,例如:

<a href="<?=$url;?>?sort=a">Sort by A-Z</a>
<a href="<?=$url;?>?sort=z">Sort by Z-A</a>

或者,再举一个例子:

<a href="<?=$url;?>?cat=1">Category 1</a>
<a href="<?=$url;?>?cat=2">Category 2</a>

或者,再举一个例子:

<a href="<?=$url;?>?page=1">1</a>
<a href="<?=$url;?>?page=2">2</a>
<a href="<?=$url;?>?page=3">3</a>
<a href="<?=$url;?>?page=4">4</a>

所以基本上,我们需要一个函数来替换URL中的特定$_GET,这样我们就不会得到重复的内容,比如:?page=2&page=3
话虽如此,它需要很聪明,以便知道参数的开头是?还是&
我们还需要它是智能的,这样我们就可以有这样的URL:

<a href="<?=$url;?>page=3">3</a> (without the ? - so it will detect automatically wether to use an `&` or a `?`

我不介意为每个preg_replace的特定$_GET参数创建不同的变量,但我正在寻找最好的方法来做到这一点。
谢谢大家。

6rvt4ljy

6rvt4ljy1#

如果我没阅读的话,我可能没看错。你知道你在一个url字符串中替换了哪个GET吗?这可能有点草率,但是...

$url_pieces = explode( '?', $url );
$var_string = $url_pieces[1].'&';
$new_url = $url_pieces[0].preg_replace( '/varName\=value/', 'newVarName=newValue', $var_string );

这是我的想法,祝你好运.

mzmfm0qo

mzmfm0qo2#

我不知道这是不是你想达到的目的,但无论如何,我还是要说:

<?php
    function mergeMe($url, $assign) {
        list($var,$val) = explode("=",$assign);
        //there's no var defined
        if(!strpos($url,"?")) {
            $res = "$url?$assign";
        } else {
            list($base,$vars) = explode("?",$url);
            //if the vars dont include the one given
            if(!strpos($vars,$var)) {
                $res = "$url&$assign";
            } else {
                $res = preg_replace("/$var=[a-zA-Z0-9_]*(&|$)/",$assign."&",$url);
                $res = preg_replace("/&$/","",$res); //remove possible & at the end
            }
        }
        //just to show the difference, should be "return $res;" instead
        return "$url <strong>($assign)</strong><br>$res<hr>";
    }

    //example
    $url1 = "http://example.com";
    $url2 = "http://example.com?sort=a";
    $url3 = "http://example.com?sort=a&page=0";
    $url4 = "http://example.com?sort=a&page=0&more=no";

    echo mergeMe($url1,"page=4");
    echo mergeMe($url2,"page=4");
    echo mergeMe($url3,"page=4");
    echo mergeMe($url4,"page=4");
?>
aamkag61

aamkag613#

改进Scuzzy 2013功能最后一块用于清洁URL查询字符串。

// merge the query string
// array_filter removes empty query array
    if ($recursive == true) {
        $merged_result = array_filter(array_merge_recursive($original_query_string, $merged_query_string));
    } else {
        $merged_result = array_filter(array_merge($original_query_string, $merged_query_string));
    }

    // Find the original query string in the URL and replace it with the new one
    $new_url = str_replace($url_components['query'], http_build_query($merged_result), $url);

    // If the last query string removed then remove ? from url 
    if(substr($new_url, -1) == '?') {
       return rtrim($new_url,'?');
    }
    return $new_url;
oxalkeyp

oxalkeyp4#

<?php
//current url: http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=a

/**
* URL Parameters : Replace query string value in a url
*
* @version 2023.02.21 Jwu
*
* @param string $queryKey Variable name 
* @param string|null $queryValue Property value
* 
* @return string
*/
function changeQueryString($queryKey, $queryValue){
    $queryStr = $_SERVER['QUERY_STRING'];
    parse_str($queryStr, $output);
    if($queryValue == null){
        unset($output[$queryKey]);
    }else{
        $output[$queryKey] = $queryValue;
    }
    $actualLink = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    return $actualLink . '?' . http_build_query($output);
}

用法:

<a href="<?php echo changeQueryString("sort",'z');?>">sort by z</a>

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=2&sort=z

<a href="<?php echo changeQueryString("page",'5');?>">Page 5</a>

http://localhost/arters?sub=Mawson&state=QLD&cat=4&page=5&sort=a

a9wyjsp7

a9wyjsp75#

我的简短和可读的方式:

function replaceGetParameters(string $url, array $newGetParameters): string {
    $url_parts = parse_url($url);
    $query = [];
    if (isset($url_parts['query'])) {
      parse_str($url_parts['query'], $query);
    }
    $query = array_merge($query, $newGetParameters);
    $url_parts['query'] = http_build_query($query);
    return $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];
  }
dsf9zpds

dsf9zpds6#

像这样的怎么样?

function merge_querystring($url = null,$query = null,$recursive = false)
{
  // $url = 'http://www.google.com.au?q=apple&type=keyword';
  // $query = '?q=banana';
  // if there's a URL missing or no query string, return
  if($url == null)
    return false;
  if($query == null)
    return $url;
  // split the url into it's components
  $url_components = parse_url($url);
  // if we have the query string but no query on the original url
  // just return the URL + query string
  if(empty($url_components['query']))
    return $url.'?'.ltrim($query,'?');
  // turn the url's query string into an array
  parse_str($url_components['query'],$original_query_string);
  // turn the query string into an array
  parse_str(parse_url($query,PHP_URL_QUERY),$merged_query_string);
  // merge the query string
  if($recursive == true)
    $merged_result = array_merge_recursive($original_query_string,$merged_query_string);
  else
    $merged_result = array_merge($original_query_string,$merged_query_string);
  // Find the original query string in the URL and replace it with the new one
  return str_replace($url_components['query'],http_build_query($merged_result),$url);
}

用法...

<a href="<?=merge_querystring($url,'?page=1');?>">Page 1</a>
<a href="<?=merge_querystring($url,'?page=2');?>">Page 2</a>
8tntrjer

8tntrjer7#

好吧,我也遇到了同样的问题,发现了这个问题,最后,我选择了自己的方法。也许它有缺陷,那么请告诉我它们是什么。我的解决方案是:

$query=$_GET;
$query['YOUR_NAME']=$YOUR_VAL;
$url=$_SERVER['PHP_SELF']. '?' .  http_build_query($query);

希望有帮助。

jpfvwuh4

jpfvwuh48#

<?php
function change_query ( $url , $array ) {
    $url_decomposition = parse_url ($url);
    $cut_url = explode('?', $url);
    $queries = array_key_exists('query',$url_decomposition)?$url_decomposition['query']:false;
    $queries_array = array ();
    if ($queries) {
        $cut_queries   = explode('&', $queries);
        foreach ($cut_queries as $k => $v) {
            if ($v)
            {
                $tmp = explode('=', $v);
                if (sizeof($tmp ) < 2) $tmp[1] = true;
                $queries_array[$tmp[0]] = urldecode($tmp[1]);
            }
        }
    }
    $newQueries = array_merge($queries_array,$array);
    return $cut_url[0].'?'.http_build_query($newQueries);
}
?>

像这样使用:

<?php
    echo change_query($myUrl, array('queryKey'=>'queryValue'));
?>

我今天早上做的,它似乎在所有情况下工作。你可以改变/添加多个查询,与数组;)

9avjhtql

9avjhtql9#

function replaceQueryParams($url, $params)
{
    $query = parse_url($url, PHP_URL_QUERY);
    parse_str($query, $oldParams);

    if (empty($oldParams)) {
        return rtrim($url, '?') . '?' . http_build_query($params);
    }

    $params = array_merge($oldParams, $params);

    return preg_replace('#\?.*#', '?' . http_build_query($params), $url);
}

$url示例:

$params示例:

[
   'foo' => 'not-bar',
]

注意:它不理解像http://example.com/page?foo=bar#section1这样带有锚点(哈希)的URL

相关问题