PHP preg_replace表达式删除URL参数

mim*_*dov 2 php preg-replace url-parameters

我想使用preg_expression从URL中删除所有出现的参数特定模式.同时删除最后一个"&"如果存在该模式看起来像:make = xy("make"是固定的;"xy"可以是任意两个字母)

例:

http://example.com/index.php?c=y&make=yu&do=ms&r=k&p=7&
Run Code Online (Sandbox Code Playgroud)

处理后preg_replace,结果应该是:

http://example.com/index.php?c=y&do=ms&r=k&p=7
Run Code Online (Sandbox Code Playgroud)

我试过用:

$url = "index.php?ok=no&make=ae&make=as&something=no&make=gr";
$url = preg_replace('/(&?lang=..&?)/i', '', $url);
Run Code Online (Sandbox Code Playgroud)

但是,这不能很好地工作,因为我在URL中有重复的make = xx(这可能发生在我的应用程序中).

Ham*_*mZa 6

您不需要RegEx:

$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
Run Code Online (Sandbox Code Playgroud)