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.
In the following code snippet shows how you can remove specific query string variable from URL in PHP.
$key = 'page'; $url = 'http://ec2-13-127-91-65.ap-south-1.compute.amazonaws.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);