How to edit URL Query String in PHP

This post provides you a PHP function which is able to edit parts of a query string.

If you want to build a pagination module for a search page, for example, containing many filtering options passed through the URL using GET parameters, you don't want to re-assemble the query string using all available parameters, but only to specify the new parameter to the current query string.

his tutorial, I'll show you how to edit the URL query string in a simple way. Using this function you'll be able to keep all parameters intact while editing, removing, or adding specified ones. Let's see how the function looks like.In t

The PHP Function

function query_editor(string $newData = "") : string {
   parse_str($newData, $newDataArray);
   $currentQuery = $_GET;
   foreach($newDataArray as $key => $value) {
      if($value == "" && isset($currentQuery[$key])) {
         unset($currentQuery[$key]);
      } else {
         $currentQuery[$key] = $value;
      }
   }
   $result = http_build_query($currentQuery);
   return "?" . $result;
}

The parameter of query_editor represents a string (using the query string standard format) containing the part of the query that should be updated.

So, you are able to:

  1. Update a parameter, by specifying its new value (eg: oldParam=newValue);
  2. Remove a parameter, by setting a blank value (eg: oldParam=)
  3. Register a new parameter, by setting it a value (eg: newParam=value).

How to use this function?

Let's look at the following example:

The current query string is:

?search=true&page=3&query=cell+phone&order_type=asc&order_by=date&manufacturer=musicer

You're right! It looks like an advanced search of an online store. The user is currently browsing the third page with results containing Cell Phones produced by Musicer company. The results are ordered by date.

ould like to add a link on the webpage to the next page with results (page parameter should become 4). We can do this as follows:We w

$new_url = query_editor("page=4");

returned value will be:The

?search=true&page=4&query=cell+phone&order_type=asc&order_by=date&manufacturer=musicer

The same way, we can delete, update or add new parameters. This function is not limited to one parameter. You can use it to make multiple changes at one time. Let's look at another example.In t

Keeping the query and the ordering parameters, we would like to remove the manufacturer filter and add a new parameter, which filters the RAM memory of the cell phones. We also need to reset the page number to 1. We'll do it like this:

$new_url = query_editor("page=1&manufacturer=&ram=2");

ou need a reliable Dedicated Server or VPS, you should definitely try InterServer Hosting. You can test InterServer for 1 Penny, for the first month, using this coupon code: WSG1PENNY.If y