通过正则表达式删除字符串中不需要的部分


Remove unwanted parts of string by regexp

我有一个字符串,看起来像这样:

position=&region_id=&radius=&companytype=&employment=&scope=&salary_from=&salary_to=&pe

是否可以preg_replace上面字符串的所有不需要的部分,除了"radius="和"scope="?

附言字符串中的所有查询参数都可以以随机方式跟随。

这是满足您需求的工作解决方案:

<?php
$str = "position=&region_id=&radius=&companytype=&employment=&scope=&salary_from=&salary_to=&pe";
// parse the string
parse_str($str,$output);
// unset the unwanted keys
unset($output['position']);
unset($output['region_id']);
unset($output['companytype']);
unset($output['employment']);
unset($output['salary_from']);
unset($output['salary_to']);
unset($output['pe']);
// transform the result to a query string again
$strClean = http_build_query($output);
echo $strClean;
?>

如果使用要保留为键的参数定义数组,则可以在parse_str后使用 array_intersect_key 来仅获取这些参数,而无需显式删除所有不需要的参数。

$wanted_keys = array('radius' => 0, 'scope' => 0);  // the values are irrelevant
parse_str($str, $parsed);
$filtered = array_intersect_key($parsed, $wanted_keys);
$result = http_build_query($filtered);

如果要定义一个数组,将所需的键作为值,可以使用array_flip将它们转换为键。

function filterQuery($query, $wanted_keys) {
    $wanted_keys = array_flip($wanted_keys);
    parse_str($query, $parsed);
    return http_build_query(array_intersect_key($parsed, $wanted_keys));
}
$result = filterQuery($str, array('radius', 'scope'));