im finding searchwords from google request urls. im using
preg_match("/[q=](.*?)[&]/", $requesturl, $match);
but it fails when the 'q' parameter is the last parameter of the string.
so 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=(.*?)(?=&|$)/
Try this:
preg_match("/q=([^&]+)/", $requesturl, $match);
A little explaining:
[q=]
will search for either q
or =
, but not one after another. [&]
is not needed as there is only one character. &
is fine. ?
operator in regex tells it to match 0 or 1 occurrences of the ** preceding** character. [^&]
will tell it to match any character except for &
. Which means you'll get all the query string until it hits &.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.