[英]php regex question for matching google searchterms in url
im finding searchwords from google request urls. 即时通讯从谷歌的请求URL中找到搜索词。 im using
我正在使用
preg_match("/[q=](.*?)[&]/", $requesturl, $match);
but it fails when the 'q' parameter is the last parameter of the string. 但是当“ q”参数是字符串的最后一个参数时,它将失败。
so i need to fetch everything that comes after 'q=', but the match must stop IF it finds '&' 所以我需要获取'q ='之后的所有内容,但是如果找到'&',则匹配必须停止
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. 编辑:我最终为匹配Google请求的网址而着陆:/ [?&] q =([^&] +)/因为有时它们的参数以q结尾。 like 'aq=0'
就像“ aq = 0”
You need /q=([^&]+)/
. 您需要
/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=(.*?)(&|$)/
. 为了构建您的查询,这是一个经过稍加修改的版本,几乎可以完成所有操作,并且与您所拥有的版本最接近:/
/q=(.*?)(&|$)/
.*?)(&| /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 ( $
). 它把
q=
出来的括号之内,因为这将匹配他们的,而不是两者一起的括号内,并在结束时,你需要匹配要么&
或字符串(结束$
)。 There are, though, a few problems with this: 但是,这有一些问题:
&
at the end of the match; &
; you don't need it. (?=&|$)
(?=&|$)
So, if you want a slightly longer query to expand what you have there, here it is: /q=(.*?)(?=&|$)/
因此,如果您希望稍长一点的查询来扩展那里的内容,则为:/
/q=(.*?)(?=&|$)/
(?= /q=(.*?)(?=&|$)/
Try this: 尝试这个:
preg_match("/q=([^&]+)/", $requesturl, $match);
A little explaining: 一些解释:
[q=]
will search for either q
or =
, but not one after another. [q=]
将搜索要么 q
或=
,但经过另一个不是一个。 [&]
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 &.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.