开发者

trim url(query string)

I have a query string like the one given below:

http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==&page=9

Now variable: page in query string can be anywhere within the query string either in beginning or middle or at end (like ?page=9 or &page=9& or &page=9).

Now, I need to remove page=9 from my query s开发者_如何学编程tring and get a valid query string.


Lots of ways this could be done, including regex (as seen below). This is the most robust method I can think of, although it is more complex than the other methods.


Use parse_url to get the query string from the url (or write your own function).

Use parse_str to convert the query string into an array

unset the key that you don't want

Use http_build_query to reassemble the array into a query string

Then reconstruct the Url (if required)


Try:

preg_replace('/page=\d+/', '', $url);


Tried writing a function for this. Seems to work:

<?php

$url = "http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==&page=9";
// prints http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==
print changeURL($url) . "\n"; 

$url = "http://localhost/project/viewMember.php?sort=Y2xhc3M=&page=9&class=Mw==";
// prints http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==
print changeURL($url) . "\n";

function changeURL($url)
{
    $arr = parse_url($url);

    $query = $arr['query'];

    $pieces = explode('&',$query);

    for($i=0;$i<count($pieces);$i++)
    {
            if(preg_match('/^page=\d+/',$pieces[$i]))
                 unset($pieces[$i]);
    }    

    $query = implode('&',$pieces);

    return "$arr[scheme]://$arr[host]$arr[user]$arr[pass]$arr[path]?$query$arr[fragment]";   
}
?>


I created these two functions:

function cleanQuery($queryLabels){
    // Filter all items in $_GET which are not in $queryLabels
    if(!is_array($queryLabels)) return;
    foreach($_GET as $queryLabel => $queryValue)
        if(!in_array($queryLabel, $queryLabels) || ($queryValue == ''))
            unset($_GET[$queryLabel]);
    ksort($_GET);
}
function amendQuery($queryItems = array()){
    $queryItems = array_merge($_GET, $queryItems);
    ksort($queryItems);
    return http_build_query($queryItems);
}

To remove the page part I would use

$_GET = amendQuery(array('page'=>null));

cleanQuery does the opposite. Pass in an array of the terms you want to keep.


function remove_part_of_qs($removeMe) 
{
    $qs = array();

    foreach($_GET as $key => $value) 
    {
        if($key != $removeMe)
        {
            $qs[$key] =  $value;
        }
    }

    return "?" . http_build_query($qs);
}

echo remove_part_of_qs("page");

This should do it, this is my first post on StackOverflow, so go easy!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜