使用PHP在单引号和双引号之间查找内容

时间:2019-11-20 08:35:03

标签: php regex string text quotes

My text "can contain" both single 'and double"' quotes. The quotes "can also be 'nested" as you can see.

预期结果

(包含3个项目的数组)

can contain
and double"
can also be 'nested

我走了多远

我不是正则表达式专家,离它远。我仍然设法使双引号之间的文本如I can "grab this" text

preg_match_all("~\"(.*?)\"~", $text, $between);
print_r($between);

有效/无效

  • 有效:This is "A text"(文本)
  • 有效:This is 'A text'(文本)
  • 有效:This is "A 'text"(A文本)
  • 有效:This is 'A "text'(“文本”
  • 无效:This is "A text(引号不均匀1)
  • 无效:This is 'A text(引号不均匀1)
  • 无效:This is "A "text"(引号3不均匀)
  • 无效:This is 'A 'text'(引号3不均匀)
  • 无效:This "is ' A " text'(相交)

附加说明

  • 如果出现错误(如非封闭引号),则可以打破(This "has "one wrong" quote
  • 我希望使用正则表达式解决方案,但是如果有更好的非正则表达式解决方案,那就很好了。

我的猜测

我的猜测是每个字符都需要循环和检查。如果以"开头,则需要将字符移至下一个"以便将其包裹起来。然后,我想需要从该位置复位以查看下一个类型的字符反复引用,直到字符串结束。

Stackoverflow上的答案无效

此答案不适用于我的问题: regex match text in either single or double quote

可以在此处查看证明:https://regex101.com/r/OVdomu/65/

1 个答案:

答案 0 :(得分:1)

您可以使用

if (preg_match_all('~(?|"([^"]*)"|\'([^\']*)\')~', $txt, $matches)) { 
    print_r($matches[1]);
}

请参见regex demoPHP demo

也支持转义引号的变体:

'~(?|"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')~s'

请参见this regex demo

(?|"([^"]*)"|\'([^\']*)\')是一个branch reset group,匹配",然后匹配除"之外的任何0+字符,然后匹配"或{{1} },然后将''以外的任何0+字符捕获,同时将匹配引号之间的所有内容捕获到组1中。