better way to replace query string value in a given url
✔ Recommended Answer
How about something like this?
function merge_querystring($url = null,$query = null,$recursive = false){ // $url = 'http://www.google.com.au?q=apple&type=keyword'; // $query = '?q=banana'; // if there's a URL missing or no query string, return if($url == null) return false; if($query == null) return $url; // split the url into it's components $url_components = parse_url($url); // if we have the query string but no query on the original url // just return the URL + query string if(empty($url_components['query'])) return $url.'?'.ltrim($query,'?'); // turn the url's query string into an array parse_str($url_components['query'],$original_query_string); // turn the query string into an array parse_str(parse_url($query,PHP_URL_QUERY),$merged_query_string); // merge the query string if($recursive == true) $merged_result = array_merge_recursive($original_query_string,$merged_query_string); else $merged_result = array_merge($original_query_string,$merged_query_string); // Find the original query string in the URL and replace it with the new one return str_replace($url_components['query'],http_build_query($merged_result),$url);}
usage...
<a href="<?=merge_querystring($url,'?page=1');?>">Page 1</a><a href="<?=merge_querystring($url,'?page=2');?>">Page 2</a>
Source: stackoverflow.com
Answered By: Scuzzy
In PHP, you can use the parse_url()
and http_build_query()
functions to parse and rebuild a URL, respectively. Here's an example of how to replace a query string value in a given URL:
php$url = "https://www.example.com/search?q=keyword&page=1";
// Parse the URL into its component parts
$urlParts = parse_url($url);
// Parse the query string into an array
parse_str($urlParts['query'], $query);
// Replace the value of the 'page' parameter
$query['page'] = 2;
// Rebuild the URL with the updated query string
$urlParts['query'] = http_build_query($query);
$newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query'];
// Output the new URL
echo $newUrl;
In this example, the original URL is parsed using parse_url()
to get its component parts. The query string is then parsed into an array using parse_str()
, and the value of the 'page' parameter is updated to 2. Finally, the updated query string is rebuilt using http_build_query()
, and the new URL is reconstructed and outputted.
This approach allows you to easily manipulate query string parameters in a given URL while preserving the rest of the URL's structure.
Comments
Post a Comment