gpt4 book ai didi

php - 正则表达式:用不在单引号中的逗号分隔,允许转义引号

转载 作者:行者123 更新时间:2023-12-04 19:52:59 29 4
gpt4 key购买 nike

我正在寻找一个使用 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% 正确匹配。 (它仍然在单引号内分隔一些逗号。)

"/'(.*?)(?<!(?<!\\\)\\\)'|[^,]+/"

最佳答案

你试过了吗str_getcsv ?无需正则表达式,它就可以完全满足您的需求。

$result = str_getcsv($str, ",", "'");

您甚至可以在 5.3 之前的 PHP 版本中实现此方法,使用来自 a comment 的代码段映射到 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;
}

}

关于php - 正则表达式:用不在单引号中的逗号分隔,允许转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246224/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com