Regex to get Keyword

Regex to get Keyword from google url


$url = "http://www.google.com/search?q=sitepoint&aq=f&aqi=g10";
$phrase = preg_match("/q=(.*)&{1}/",$url, $m);
echo $m[0];

That gives me something like
?q=sitepoint&aq=f&aqi=g10

when all i want is
sitepoint

Any help would be much appreciated as always :slight_smile:

See [fphp]parse_url/fphp and [fphp]parse_str/fphp. :wink:


<?php
$elements = array();

parse_str(
    parse_url(
        'http://www.google.com/search?q=sitepoint&aq=f&aqi=g10',
        PHP_URL_QUERY
    ),
    $elements
);

print_r(
    $elements
);

/*
    Array
    (
            [q] => sitepoint
            [aq] => f
            [aqi] => g10
    )
*/
?>

However, if you’re insistent on still using RegExp you would be looking at something like…


~(?<=[?&]q=)([^&]+)~i

The * is “greedy”. Read more here: http://www.regular-expressions.info/repeat.html

Try this expression: /q=(.*?)&/

And you’ll find what you need in $m[1]

Hey that php worked just fine.

You really are a php ninja.

Me and my little brother loved ninjas. If you haven’t yet check out the music vid “enter the ninja” from die antword. Its awesome :slight_smile:

Thanks so much man. :smiley:

o and thanks for the other response guido.

What answer is less resource intensive?

Probably preg_match I’d say. Half as many function calls and a fairly basic/standard pattern too.