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

Find content between both single and double quotes with PHP

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);

有效/无效

补充说明

我的猜测

我的猜测是每个字符都需要循环检查。如果它以 " 开头,它需要将字符步进到下一个 " 以便将其包装起来。然后我想它需要从那个位置重新设置以查看下一个类型是什么quote 是,直到字符串结束。

Whosebug 上的答案不起作用

这个答案解决我的问题:

证明可以在这里看到:https://regex101.com/r/OVdomu/65/

您可以使用

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

参见regex demo and the PHP demo

也支持转义引号的变体:

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

参见 this regex demo

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