REGEX:用逗号分隔,不是单引号,允许转义引号

Jor*_*anL 2 php regex

我正在寻找一个使用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')
Run Code Online (Sandbox Code Playgroud)

这应该产生如下匹配:

(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')
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多很多正则表达式...我现在看起来像这样,虽然它不能正确匹配100%.(它仍然在单引号内分割一些逗号.)

"/'(.*?)(?<!(?<!\\\)\\\)'|[^,]+/"
Run Code Online (Sandbox Code Playgroud)

And*_*y E 7

你试过str_getcsv吗?它完全符合您的需要而无需正则表达式.

$result = str_getcsv($str, ",", "'");
Run Code Online (Sandbox Code Playgroud)

您甚至可以在早于5.3的PHP版本中实现此方法,fgetcsv从文档中的注释映射到此片段:

if (!function_exists('str_getcsv')) {

    function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = null, $eol = null) {
        $temp = fopen("php://memory", "rw");
        fwrite($temp, $input);
        fseek($temp, 0);
        $r = fgetcsv($temp, 4096, $delimiter, $enclosure);
        fclose($temp);
        return $r;
    }

}
Run Code Online (Sandbox Code Playgroud)