How to Remove a Specific Parameter from URL Query String using PHP

Stripping query parameter is very useful when you want to create a URL dynamically based on some conditions. The preg_replace() function is the easiest way to remove a specific parameter and its value from URL query string using PHP. PHP preg_replace() function searches string for matches to pattern and replace with the replacement. Use preg_replace() with REGEX to remove parameter from query string using PHP.

The following code snippet shows how you can remove specific query string variable from URL in PHP.

$key 'page';
$url 'https://www.codexworld.com/?type=product&page=5';

// Remove specific parameter from query string
$filteredURL preg_replace('~(\?|&)'.$key.'=[^&]*~''$1'$url);

The following example code shows how you can remove a specific parameter from the query string of the current URL using PHP.

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" "http://";
$currentURL $protocol $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

$key 'page';

// Remove specific parameter from query string
$filteredURL preg_replace('~(\?|&)'.$key.'=[^&]*~''$1'$currentURL);

1 Comment

  1. Zarto Said...

Leave a reply

keyboard_double_arrow_up