是否有一个PHP库来处理URL参数的添加,删除或替换?

时间:2022-08-24 11:55:33

when we add a param to the URL

当我们向URL添加一个参数时

$redirectURL = $printPageURL . "?mode=1";

$ redirectURL = $ printPageURL。 “?模式= 1”;

it works if $printPageURL is "http://www.somesite.com/print.php", but if $printPageURL is changed in the global file to "http://www.somesite.com/print.php?newUser=1", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files.

如果$ printPageURL是“http://www.somesite.com/print.php”,但是如果$ printPageURL在全局文件中更改为“http://www.somesite.com/print.php?newUser= 1“,然后URL变得糟糕。如果项目有300个文件,并且有30个文件以这种方式追加参数,我们需要更改所有30个文件。

the same if we append using "&mode=1" and $printPageURL changes from "http://www.somesite.com/print.php?new=1" to "http://www.somesite.com/print.php", then the URL is also badly formed.

如果我们使用“&mode = 1”追加并且$ printPageURL从“http://www.somesite.com/print.php?new=1”更改为“http://www.somesite.com/print.php” “,那么网址也很糟糕。

is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer?

PHP中有一个库会自动处理“?”和“&”,甚至检查现有的param是否已经存在并删除了那个,因为它将被后者替换,如果URL持续增长则不好?

Update: of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?

更新:几个有用的答案,似乎没有预先存在的函数addParam($ url,$ newParam),所以我们不需要写它?

6 个解决方案

#1


Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.

使用parse_url()组合来分解URL,使用parse_str()来分解查询字符串,使用http_build_query()来重建查询字符串。之后,您可以从您从parse_url()获得的原始片段和使用http_build_query()构建的新查询字符串重建整个URL。随着查询字符串被分解为关联数组(键值对),修改查询就像在PHP中修改数组一样简单。

EDIT

$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
 * $params = array(
 *     'mode'    => '1'
 *     'newUser' => '1'
 * )
 */
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"

#3


http://www.addedbytes.com/php/querystring-functions/ is a good place to start

http://www.addedbytes.com/php/querystring-functions/是一个很好的起点

EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php

编辑:还有http://www.php.net/manual/en/class.httpquerystring.php

for example:

$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc')); 
$url = "yourfile.php" . $http->toString();

#4


None of these solutions work when the url is of the form: xyz.co.uk?param1=2&replace_this_param=2 param1 gets dropped all the time .. which means it never works EVER!

当url具有以下形式时,这些解决方案都不起作用:xyz.co.uk?param1 = 2&replace_this_param = 2 param1一直被丢弃..这意味着它永远不会工作!

If you look at the code given above:

如果你看一下上面给出的代码:

function addParam($url, $s) {
    return adjustParam($url, $s);
}

function delParam($url, $s) {
    return adjustParam($url, $s);           
}

These functions are IDENTICAL - so how can one add and one delete?!

这些函数是IDENTICAL - 所以如何添加和删除?!

#5


using WishCow and sgehrig's suggestion, here is a test:

使用WishCow和sgehrig的建议,这是一个测试:

(assuming no anchor for the URL)

(假设URL没有锚点)

<?php

    echo "<pre>\n";

    function adjustParam($url, $s) {        
        if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
        else $urlWithoutParams = $url;  

        parse_str(parse_url($url, PHP_URL_QUERY), $params);

        if (strpos($s, '=') !== false) {
            list($var, $value) = split('=', $s);
            $params[$var] = urldecode($value);
            return $urlWithoutParams . '?' . http_build_query($params);      
        } else {
            unset($params[$s]);
            $newQueryString = http_build_query($params);
            if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;      
            else return $urlWithoutParams;
        }

    }

    function addParam($url, $s) {
        return adjustParam($url, $s);
    }

    function delParam($url, $s) {
        return adjustParam($url, $s);       
    }

    echo "trying add:\n";

    echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n"; 
    echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";  

    echo "\n", "now trying delete:\n";

    echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";   
    echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";     
    echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";   

?>

and the output is:

输出是:

trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3

now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1

#6


You can try this:

你可以试试这个:

function removeParamFromUrl($query, $paramToRemove)
{
    $params = parse_url($query);
    if(isset($params['query']))
    {
        $queryParams = array();
        parse_str($params['query'], $queryParams);
        if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
        $params['query'] = http_build_query($queryParams);
    }
    $ret = $params['scheme'].'://'.$params['host'].$params['path'];
    if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
    return $ret;
}

#1


Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.

使用parse_url()组合来分解URL,使用parse_str()来分解查询字符串,使用http_build_query()来重建查询字符串。之后,您可以从您从parse_url()获得的原始片段和使用http_build_query()构建的新查询字符串重建整个URL。随着查询字符串被分解为关联数组(键值对),修改查询就像在PHP中修改数组一样简单。

EDIT

$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
 * $params = array(
 *     'mode'    => '1'
 *     'newUser' => '1'
 * )
 */
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"

#2


#3


http://www.addedbytes.com/php/querystring-functions/ is a good place to start

http://www.addedbytes.com/php/querystring-functions/是一个很好的起点

EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php

编辑:还有http://www.php.net/manual/en/class.httpquerystring.php

for example:

$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc')); 
$url = "yourfile.php" . $http->toString();

#4


None of these solutions work when the url is of the form: xyz.co.uk?param1=2&replace_this_param=2 param1 gets dropped all the time .. which means it never works EVER!

当url具有以下形式时,这些解决方案都不起作用:xyz.co.uk?param1 = 2&replace_this_param = 2 param1一直被丢弃..这意味着它永远不会工作!

If you look at the code given above:

如果你看一下上面给出的代码:

function addParam($url, $s) {
    return adjustParam($url, $s);
}

function delParam($url, $s) {
    return adjustParam($url, $s);           
}

These functions are IDENTICAL - so how can one add and one delete?!

这些函数是IDENTICAL - 所以如何添加和删除?!

#5


using WishCow and sgehrig's suggestion, here is a test:

使用WishCow和sgehrig的建议,这是一个测试:

(assuming no anchor for the URL)

(假设URL没有锚点)

<?php

    echo "<pre>\n";

    function adjustParam($url, $s) {        
        if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
        else $urlWithoutParams = $url;  

        parse_str(parse_url($url, PHP_URL_QUERY), $params);

        if (strpos($s, '=') !== false) {
            list($var, $value) = split('=', $s);
            $params[$var] = urldecode($value);
            return $urlWithoutParams . '?' . http_build_query($params);      
        } else {
            unset($params[$s]);
            $newQueryString = http_build_query($params);
            if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;      
            else return $urlWithoutParams;
        }

    }

    function addParam($url, $s) {
        return adjustParam($url, $s);
    }

    function delParam($url, $s) {
        return adjustParam($url, $s);       
    }

    echo "trying add:\n";

    echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n"; 
    echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
    echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";  

    echo "\n", "now trying delete:\n";

    echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";   
    echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";     
    echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";   

?>

and the output is:

输出是:

trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3

now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1

#6


You can try this:

你可以试试这个:

function removeParamFromUrl($query, $paramToRemove)
{
    $params = parse_url($query);
    if(isset($params['query']))
    {
        $queryParams = array();
        parse_str($params['query'], $queryParams);
        if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
        $params['query'] = http_build_query($queryParams);
    }
    $ret = $params['scheme'].'://'.$params['host'].$params['path'];
    if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
    return $ret;
}