Sergei Pavlov
Sergei Pavlov

Reputation: 51

Remove unwanted parts of string by regexp

I have a string which looks like this:

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

Is it possibe to preg_replace all unwanted parts of string above except "radius=" and "scope=" ?

P.S. All query params in the string may follow in random way.

Upvotes: 0

Views: 95

Answers (2)

Don't Panic
Don't Panic

Reputation: 41810

If you define an array using the parameters you want to keep as keys, you can use array_intersect_key after parse_str to get only those parameters without needing to explicitly remove all the unwanted ones.

$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);

If you want to define an array with the wanted keys as values, you can use array_flip to convert them to keys.

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'));

Upvotes: 0

Nutshell
Nutshell

Reputation: 8537

Here's a working solution to your need :

<?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;

?>

Upvotes: 2

Related Questions