【发布时间】:2010-11-22 14:09:28
【问题描述】:
我正在寻找一个在 PHP 5 中使用 preg_match_all 的正则表达式,它允许我用逗号分割字符串,只要逗号不存在于单引号内,允许转义单引号。示例数据是:
(some_array, 'some, string goes here','another_string','this string may contain "double quotes" but, it can\'t split, on escaped single quotes', anonquotedstring, 83448545, 1210597346 + '000', 1241722133 + '000')
这应该会产生如下所示的匹配:
(some_array
'some, string goes here'
'another_string'
'this string may contain "double quotes" but, it can\'t split, on escaped single quotes'
anonquotedstring
83448545
1210597346 + '000'
1241722133 + '000')
我尝试了很多很多正则表达式...我当前的正则表达式看起来像这样,尽管它没有 100% 正确匹配。 (它仍然在单引号内分割一些逗号。)
"/'(.*?)(?<!(?<!\\\)\\\)'|[^,]+/"
【问题讨论】:
-
这个可以做到,但比大多数人想象的要难;看起来你现在已经感受到了困难。在 PHP 中真的没有库函数来处理这个问题吗? Perl中有。如果到那时你还没有得到一个好的答案,我可能会尝试稍后为你整理正则表达式。