从包含查询字符串的 URL 字符串中获取特定值
我正在从 google 请求 URL 中查找搜索词。
我正在使用,
preg_match("/[q=](.*?)[&]/", $requesturl, $match);
但当“q”参数是字符串的最后一个参数时,它会失败。
我需要获取“q=”之后的所有内容,但如果找到“&”,则比赛必须停止
怎么做呢?
编辑:我最终找到了这个来匹配谷歌请求URL:
/[?&]q=([^&]+)/
因为有时它们有一个以 q
结尾的参数。就像aq=0
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
/q=([^&]+)/
。诀窍是匹配查询中除&
之外的所有内容。为了构建您的查询,这是一个稍作修改的版本,它(几乎)可以实现该技巧,并且它最接近你那里有什么:
/q=(.*?)(&|$)/
。它将q=
放在括号之外,因为在括号内它将匹配其中一个,而不是同时匹配,最后您需要匹配其中一个&
或字符串结尾 ($
)。不过,这样做也存在一些问题:&
;你不需要它。要解决此问题,您可以使用 lookahead 查询:(?=& |$)
因此,如果您想要一个稍长的查询来扩展那里的内容, 这里是:
/q=(.*?)(?=&|$)/
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 theq=
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=(.*?)(?=&|$)/
试试这个:
稍微解释一下:
[q=]
将搜索任一q
或=
,但不是一个又一个。[&]
,因为只有一个字符。&
没问题。?
运算符告诉它匹配 ** 前面的 ** 字符的 0 或 1 次出现。[^&]
会告诉它匹配&
之外的任何字符除外。这意味着您将获得所有查询字符串,直到遇到 &。Try this:
A little explaining:
[q=]
will search for eitherq
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 &.