Search code examples
phpregexquery-stringtext-extractionurl-parsing

Get a particular value from a URL string containing querystring


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


Solution

  • 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:

    1. sometimes you will have an extra & at the end of the match; you don't need it. To solve this problem you can use a lookahead query: (?=&|$)
    2. it introduces an extra group at the end (not necessarily bad, but can be avoided) -- actually, this is fixed by 1.

    So, if you want a slightly longer query to expand what you have there, here it is: /q=(.*?)(?=&|$)/