php - 从查询字符串中删除已知值参数
问题描述
我正在使用 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));
有没有其他方法可以实现这一目标?
解决方案
一个更简单的解决方案(恕我直言,更易于维护)是用于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);
推荐阅读
- python - 使用 Python + lxml (xpath) 从网站抓取/提取文本并打印
- c# - 如何将两个列表相互组合?
- python - python循环遍历图像列表并将它们分组合并
- sql - 如何在熊猫的postgresql中对多个表进行聚合和分组
- typescript - Typescript 中的复杂类型
- javascript - javascript else 语句仅在正确填写所有内容时才返回 true
- angular - ./server.ts 中的错误未找到模块:错误:无法解析“./dist/server/main.bundle”
- php - 解析错误:语法错误,意外的 ';' 在第 24 行的 /etc/zabbix/web/zabbix.conf.php 中
- android - 适用于 Android 的 C/C++ 内存分配边界对齐
- ruby-on-rails - 如何 RSpec 测试设置的错误通知