View Full Version : How to replace the value inside a URL with another one?

03-05-2010, 10:18 AM
Hello, I have a problem i'm stuck on. I am trying to write a function that will take the current URL and change the value of "page" to the value being passed into the method. So, for example, if the current URL is "http://mysite.com/?go=search&page=12&q=on", and the parameter being passed is 4, I would would want it to change it to "http://mysite.com/?go=search&page=4&q=on". What is the best way to do this?

I guess it would be something like this:

function changePage($value)
$URL = getCurrURL(); // helper function

// what do I do next? lol

Thanks in advance for your help!

03-05-2010, 11:09 AM

Please check http_build_url (http://www.php.net/manual/en/function.http-build-url.php) and similar functions: parse_url(), parse_str(), http_build_query().

03-05-2010, 04:25 PM
Yeah I would favour the functions above, although you could use a regular expression along with preg_replace to replace the value

$URL = preg_replace('/\bpage=\d+/', 'page='.$value, $URL);