首页 > 解决方案 > 从查询字符串中删除已知值参数

问题描述

我正在使用 PHP 脚本。

我有一个类似http://example.com?tag=test1&creative=165953&creativeASIN=B07BH2N15X&linkCode=df0&ascsubtag=test2的网址。在查询字符串 tag=test1 和 ascsubtag=test2 中,我知道值 test1 和 test2 不是关键。现在我想从 URL 中删除键标签和 ascsubtag 以进行敏感化。

预期输出为http://example.com?creative=165953&creativeASIN=B07BH2N15X&linkCode=df0。我怎样才能以简单的方式实现这一目标。

我试过下面的代码,

$a = parse_url("http://example.com?tag=test1&creative=165953&creativeASIN=B07BH2N15X&linkCode=df0&ascsubtag=test2");
parse_str($a['query'], $queryStr);
$interchanged = array_flip($queryStr);
unset($interchanged['test1']);
unset($interchanged['test2']);
echo $a['scheme'] . "://" . $a['host'] . (isset($pURL['path']) ? $pURL['path'] : '') . "?" . http_build_query(array_flip($interchanged));

有没有其他方法可以实现这一目标?

标签: phpregex

解决方案


一个更简单的解决方案(恕我直言,更易于维护)是用于array_filter()删除原始代码中不需要的任何值,而不是使用翻转/取消设置/翻转方法...

$a = parse_url("http://example.com?tag=test1&creative=165953&creativeASIN=B07BH2N15X&linkCode=df0&ascsubtag=test2");
parse_str($a['query'], $queryStr);
$interchanged = array_filter($queryStr, function($value) { return ( $value != "test1" && $value != "test2");});
echo $a['scheme'] . "://" . $a['host'] . (isset($pURL['path']) ? $pURL['path'] : '') . "?" . http_build_query($interchanged);

推荐阅读