views:

100

answers:

4

Hi All, what we can do to remove page=2& From:

"page=2&param1=value1&param2=value2" or
"param1=value1&page=2&param2=value2".

become:

"param1=value1&param2=value2" or
"param1=value1&param2=value2".

in case of page=2, 2 is any natural no. i.e. (0 to 32000).

Regards,

A: 

If I understood you correctly, this will let you remove an arbitrary page (as long as you know the number):

function replacePage($querystring, $page = 1) {
    return str_replace('page='.$page.'&', '', $querystring);
} 

As a side note, using regular expressions is not the optimum way to code if they can be avoided. They are slow and should be replaced with other methods such as str_replace or tokenizing where possible. Personally I'd use my method If I knew what page I had to remove from the query string as it will run much faster than a preg_replace.

cballou
ok, nice idea, but i can't see the result? thank you
jones
did you echo the data? i.e. `echo replacePage($myQueryString, 2)`.
cballou
+1  A: 
 $str = trim(preg_replace("/\bpage=\d+&?/", "", $str), "$");

The regexp:

\b        # Match a "boundary" point (start of new word)
page=     # Match 'page='
\d+       # Match 1 or more digits
&?        # Match a '&' if it exists

The trim around the outside will remove any trailing & that might be leftover.

If you want to trim anything you can replace the \d+ with [^&]+ to match any characters other than &.

 $str = trim(preg_replace("/\bpage=[^&]+&?/", "", $str), "$");
gnarf
vava
@vava - added a trim to take care of that case
gnarf
What if the visitor has manually typed in a page that is not a number? how if to parse the query string, explicitly remove the key in question, and rebuild it, but thank you for your input
jones
+10  A: 

You can use parse_str to parse the string to an array, unset page from the array, and then use http_build_query to reconstruct the result.

Code example:

$str = 'page=2&param1=value1&param2=value2';
$arr = array();
parse_str($str, $arr);
unset($arr['page']);
echo http_build_query($arr);
Mark Byers
Creating, unsetting, and imploding seems like a bit of overkill to me but it would look a hell of a lot cleaner than regex.
cballou
Thank You Mark for you input so far, but how to use http_build_query related to my question, and used for pafination?
jones
I have provided a code example.
Mark Byers
A: 

using explode ?

$urlString = "page=2&param1=value1&param2=value2";
$arr = explode('&',$urlString);
print_r( $arr );
foreach( $arr as $var => $val ) {
    if( substr( $val, 0, 6 ) == 'param2' ) {
        unset( $arr[ $var ] );
    }
}
$urlString = implode('&',$arr);
FrankBr
output of your code: Array ( [0] => page=2 [1] => param1=value1 [2] => param2=value2 ) it's look not seem like my first posting, but thank for your input
jones