从包含查询字符串的 URL 字符串中获取特定值

发布于 2024-11-30 16:42:35 字数 356 浏览 1 评论 0原文

我正在从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

惜醉颜 2024-12-07 16:42:35

您需要/q=([^&]+)/。诀窍是匹配查询中除 & 之外的所有内容。

为了构建您的查询,这是一个稍作修改的版本,它(几乎)可以实现该技巧,并且它最接近你那里有什么:/q=(.*?)(&|$)/。它将 q= 放在括号之外,因为在括号内它将匹配其中一个,而不是同时匹配,最后您需要匹配其中一个 & 或字符串结尾 ($)。不过,这样做也存在一些问题:

  1. 有时在比赛结束时你会看到一个额外的 &;你不需要它。要解决此问题,您可以使用 lookahead 查询: (?=& |$)
  2. 它在末尾引入了一个额外的组(不一定是坏事,但可以避免)——实际上,这是通过 1 修复的。

因此,如果您想要一个稍长的查询来扩展那里的内容, 这里是: /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 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=(.*?)(?=&|$)/

赠佳期 2024-12-07 16:42:35

试试这个:

preg_match("/q=([^&]+)/", $requesturl, $match);

稍微解释一下:

  • [q=]将搜索任一q=,但不是一个又一个。
  • 不需要 [&],因为只有一个字符。 & 没问题。
  • 正则表达式中的 ? 运算符告诉它匹配 ** 前面的 ** 字符的 0 或 1 次出现。
  • [^&] 会告诉它匹配 & 之外的任何字符除外。这意味着您将获得所有查询字符串,直到遇到 &。

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.
  • the ? 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 &.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文