BIOS,Windows, Linux, Software,Security, Domains, Web Hosting

Parse and Change Query String with Multiple Values in PHP

We often need to rebuild the url query string while we  are developing PHP, and we know there many methods to accomplish it. Here I write two samples as your reference. If you have a simple, reasonable opinions, please leave to me without any hesitation.

Here are somequery url samples:

//test?page=123
//test?page=123&a=4
//test?a=4&page=123&b=1
//test?a=4&b=1&page=123

Now, I'll replace the page=123 with a new page variable.

1. Parse query string

$url=$_SERVER["REQUEST_URI"];//request url address
$purl=parse_url($url);
$oldq=$purl['query'];//same as $_SERVER["QUERY_STRING"]

The oldq variable is the total query string, such as "a=4&page=123&b=1", etc. If you do not familar with $_SERVER, you will find more by these codes:

echo '<pre>';
printf_r($_SERVER);

2. Repalce query varaible

Method A: Using parse_str() function

$arrTmp=array();
parse_str($oldq,$arrTmp); //To array
unset($arrTmp['page']);
$newq = http_build_query($arrTmp);//build again
$newUrl=str_replace($oldq,$newq,$url);//same as $_SERVER['SCRIPT_NAME'].'?'.$newq;

Method B: Using preg_replace() function

As we know the page variable will be followed by numbers, so the syntax may be like these:

$newq=preg_replace("/^page=\d+($|&)/","",$oldq);
$newq=preg_replace("/&page=\d+/","",$newq);
$newUrl=str_replace($oldq,$newq,$url);

3. Add new query varialble

Here I add a new page parameter (page=345).

if($newq!='')
     $url .= "&page=345";
else
     $url .= "page=345";//`?` is left after url str_replaced

 

4. OK, finished!

Related Articles

Comments(0)  

Leave a Reply

Subscribe to BootBeta Comments RSS feed to receive notification of latest comments posted.

Subscriptions

  • Enter Email Address:

Recent Post

Copyright@ 2010-2014 Bootbeta All Rights Reserved.
HooBlog Ver 1.5 Build 20140530