billyhafiz billyhafiz - 2 months ago 14
PHP Question

Is it possible to create a reliable php regex to get search query string from a Google url?

A possible url from Google may look like:

https://www.google.co.in/search?q=user%27s+search+query&oq=user%27s+search+query&gs_l=serp.3...

so the regex will produce: "user's search query".

Answer

Get the query string, then parse the vars into an array. It should always be q:

parse_str(parse_url($url, PHP_URL_QUERY), $result);

echo $result['q'];

The query string will be:

q=user%27s+search+query&oq=user%27s+search+query&gs_l=serp.3

And the $result['q'] will be:

user's search query

And the full $result:

Array
(
    [q] => user's search query
    [oq] => user's search query
    [gs_l] => serp.3
)
Comments