I'm finding search words from google request URLs.
I'm using
preg_match("/[q=](.*?)[&]/", $requesturl, $match);
but it fails when the 'q' parameter is the last parameter of the string.
I need to fetch everything that comes after 'q=', but the match must stop IF it finds '&'
How to do that?
EDIT: I eventually landed on this for matching google request URL:
/[?&]q=([^&]+)/
Because sometimes they have a param that ends with q
. like aq=0
You need /q=([^&]+)/
. The trick is to match everything except &
in the query.
To build on your query, this is a slightly modified version that will (almost) do the trick, and it's the closest to what you have there: /q=(.*?)(&|$)/
. It puts the q=
out of the brackets, because inside the brackets it will match either of them, not both together, and at the end you need to match either &
or the end of the string ($
). There are, though, a few problems with this:
&
at the end of the match; you don't need it. To solve this problem you can use a lookahead query: (?=&|$)
So, if you want a slightly longer query to expand what you have there, here it is: /q=(.*?)(?=&|$)/