views:

44

answers:

3

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?

A: 

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

Mr-sk
+1  A: 

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
cletus
How CPU intensive is this? preg is a little slow, no?
Yegor
If not used thousands of times in a loop, totally, totally harmless.
Pekka
+1 for nice, ready-to-run solution. Just the transformation to `ge_xxx` is missing but the OP has not defined that yet.
Pekka
@Yegor: `preg_grep()` is a convenience. You can do it without using a loop and checking what the array key starts with but unless you're doing this tens of thousands of times in a single script execution it's not even worth worrying about.
cletus
Works perfect! Thanks!
Yegor
+2  A: 

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.

Pekka