PHP如何删除URL查询字符串中的特定参数

当我们希望根据某些条件动态创建URL时,剥离查询参数非常有用。
preg_replace()函数是使用PHP从URL查询字符串中删除特定参数的最简单方法及其值。
php preg_replace()函数搜索匹配的字符串以模式和替换替换。
使用preg_replace()使用Regex删除使用PHP从查询字符串中的参数。

在以下代码中,展示如何从PHP中从URL中删除特定的查询字符串变量。

$key = 'page';
$url = 'https://www.onitroad.com/?type=product&page=5';
//Remove specific parameter from query string
$filteredURL = preg_replace('~(\?|&)'.$key.'=[^&]*~', '', $url);

以下示例代码显示了如何使用PHP从当前URL的查询字符串中删除特定参数。

$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.'=[^&]*~', '', $currentURL);
日期:2020-06-02 22:15:58 来源:oir作者:oir