PHP preg_replace expression to remove URL parameter
php, preg-replace, url-parameters
Solution
You don't need RegEx for this:
$url = "http://example.com/index.php?ok=no&make=ae&make=as&something=no&make=gr&";
list($file, $parameters) = explode('?', $url);
parse_str($parameters, $output);
unset($output['make']); // remove the make parameter
$result = $file . '?' . http_build_query($output); // Rebuild the url
echo $result; // http://example.com/index.php?ok=no&something=no
Problem
I wanted to remove all occurrences of specific pattern of a parameter from a URL using preg_expression. Also removing the last "&" if exist The pattern looks like: make=xy ("make" is fixed; "xy" can be any two letters) Example: ``` http://example.com/index.php?c=y&make=yu&do=ms&r=k&p=7& ``` After processing `preg_replace`, the outcome should be: ``` http://example.com/index.php?c=y&do=ms&r=k&p=7 ``` I tried using: ``` $url = "index.php?ok=no&make=ae&make=as&something=no&make=gr"; $url = preg_replace('/(&?lang=..&?)/i', '', $url); ``` However, this did not work well because I have duplicates of make=xx in the URL (which is a case that could happen in my app).