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
)我的猜测是每个字符都需要循环和检查。如果以"
开头,则需要将字符移至下一个"
以便将其包裹起来。然后,我想需要从该位置复位以查看下一个类型的字符反复引用,直到字符串结束。
此答案不不适用于我的问题: regex match text in either single or double quote
可以在此处查看证明:https://regex101.com/r/OVdomu/65/
答案 0 :(得分:1)
您可以使用
if (preg_match_all('~(?|"([^"]*)"|\'([^\']*)\')~', $txt, $matches)) {
print_r($matches[1]);
}
请参见regex demo和PHP demo。
也支持转义引号的变体:
'~(?|"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')~s'
请参见this regex demo。
(?|"([^"]*)"|\'([^\']*)\')
是一个branch reset group,匹配"
,然后匹配除"
之外的任何0+字符,然后匹配"
或{{1} },然后将'
和'
以外的任何0+字符捕获,同时将匹配引号之间的所有内容捕获到组1中。