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
我已经走了多远
虽然我不是正则表达式专家,但我仍然成功地获取了双引号之间的文本,例如我可以“获取这个”文本
。
preg_match_all("~\"(.*?)\"~", $text, $between);
print_r($between);
有效/无效
- 有效:
This is "A text"
(A text) - 有效:
This is 'A text'
(A text) - 有效:
This is "A 'text"
(A 'text) - 有效:
This is 'A "text'
(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/
preg_match_all('~(?|"([^"]*)"|\'([^\']*)\')~', $txt, $matches); print_r($matches[1]);
在遇到无效(不对称引号)的情况下会中断。 - Wiktor Stribiżew