简体   繁体   English

在PHP正则表达式中匹配双引号

[英]matching doublequotes in PHP regex

I'm trying to write what should be a fairly simple regex for a PHP script to match tag: followed by a word in double quotes. 我正在尝试为PHP脚本写一个与tag:匹配的正则表达式,后面是一个双引号。 I want it to return just the value inside the quotes, minus the quotes themselves ( tag:"whatever" returns whatever ). 我希望它只返回引号内的值,减去引号本身( tag:"whatever"返回whatever )。

I have a search box on a page which submits the form data (via GET, if that matters) to itself, and runs a PHP script on it. 我在页面上有一个搜索框,它向自身提交表单数据(如果需要的话,通过GET),并在其上运行PHP脚本。 This is what happens inside the script: 这是脚本内部发生的情况:

$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:\"([\w]+)\"/", $q, $tags);

I want it to match something like tag:"this" , but when I search for that, I get no matches: 我希望它匹配tag:"this"类的东西,但是当我搜索它时,没有找到匹配项:

//print_r($tags) yields:
Array
(
  [0] => Array
    (
    )
  [1] => Array
    (
    )
)

I figured it might be an escaping issue, so I also tried 我认为这可能是一个逃避的问题,所以我也尝试了

$q = stripslashes(urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING)));
preg_match_all("/tag:\"([\w]+)\"/", $q, $tags);

and

$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:\\\"([\w]+)\\\"/", $q, $tags);

Both of these return the same array of two empty arrays. 这两个都返回两个空数组的相同数组。

In desperation I even tried it with single quotes (and searching for tag:'this' ), which I didn't need to escape, but this also returned nothing: 无奈之下,我什至尝试使用单引号(并搜索tag:'this' ),但我并不需要转义,但这也没有返回任何结果:

$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:'([\w]+)'/", $q, $tags);

Removing the quotes, incidentally, makes it work fine: 顺便删除引号可以使其正常工作:

//searching for tag:something with preg_match_all("/tag:([\w]+)/", $q, $tags); yields:
Array
(
  [0] => Array
    (
      [0] => tag:something
    )
  [1] => Array
    (
      [0] => something
    )
)

I'm almost certain I'm making a really foolish mistake, but stare at it as I might, I can't figure out what. 我几乎可以肯定我犯了一个非常愚蠢的错误,但是我可能会盯着它看,我不知道该怎么办。 I have tried searching for it, but was unable to find anyone with the same problem. 我尝试搜索它,但是找不到任何有相同问题的人。 This further leads me to think the problem is trivial, and that I'm being dim. 这进一步使我认为问题是微不足道的,而且我很沮丧。 Help! 救命!

Use the following: 使用以下内容:

preg_match('|tag:"(\w+)"|', $str, $results);

When using single quotes in PHP, it saves you the need to escape the double quotes, thus saving you the confusion over what to escape and what is a character in RegEx. 在PHP中使用单引号时,它省去了对双引号进行转义的需要,从而避免了您对要转义的内容和RegEx中的字符感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM