user15063
user15063

Reputation:

Elegant solution to read and transform query string in php?

I have a query string such as this:

file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3

I need to extract all the genres mentioned in the string, in this case its

genre1, genre4, genre19 and genre18

and output them into a string such as

ge1_ge4_ge19_ge18

What would be a good solution for this?

Upvotes: 1

Views: 227

Answers (3)

cletus
cletus

Reputation: 625237

If you want the parameters passed by query string to the currently executing script then you simply need:

$genres = preg_grep('!^genre!', array_keys($_GET));
$out = implode('_', $genres);

Here you're filtering out all the parameters that start with genre using preg_grep() and getting a list of parameter names using array_keys().

If you have a URL you need to parse then use this snippet:

$url = 'file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
$genres = preg_grep('!^genre!', array_keys($params));
echo implode('_', $genres);

The difference here is that you use parse_url() to extract the query string and parse_str() to parse the query string.

Output:

genre1_genre4_genre19_genre181

Upvotes: 2

Pekka
Pekka

Reputation: 449613

parse_str() with the optional $arr argument is specifically built for exploding a query string properly:

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

It can even deal with array arguments.

http_build_query() can glue an array back together with a custom $arg_separator but to get the output specifically as you want it, you will have to manually iterate through the arguments to make the transformation.

Upvotes: 2

mr-sk
mr-sk

Reputation: 13417

You could explode on the '=' then join on '_'.

Upvotes: 0

Related Questions