[PHP] Dynamically Modify URL Query String
I have to work with URL query string frequently. Often, I have to change and reconstruct the query portion based on certain rules. I wrote a function that takes in a URL string and an associative array, combines them and returns a new URL string. The resultant string can be used in <anchor> tags and also for HTTP GET request.
Usage example:
$url = 'http://www.example.com/index.php?id=123&name=orange#anchor';
$query1 = 'id=246&category=fruit shop';
$query2 = array('id'=>246, 'category'=>'fruit shop');
echo modifyQuery($url, $query1);
echo "<br />";
echo modifyQuery($url, $query2);
The $query parameter can be either a string or an associative array. In my usage example, both function calls return the same output.
NOTE: A valid URL string may contain username, password and port number. My function will not work with this information, but you can easily modify the function to retain these information. Have you noticed that the id has been changed from 123 to 246? The function’s $query parameter will appends+overwrites the query string.