这对于preg_split 几乎是不可能的,因为您无法从字符串的中间判断您是否在引号之间。但是,preg_match_all 可以胜任。
单一类型报价的简单解决方案:
function quoted_explode($subject, $delimiter = ',', $quote = '\'') {
$regex = "(?:[^$delimiter$quote]|[$quote][^$quote]*[$quote])+";
preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
return $matches[0];
}
如果你向该函数传递某些特殊字符(\^-],根据http://www.regular-expressions.info/reference.html),该函数会出现各种问题,因此你需要转义这些字符。这是一个通用的解决方案,它可以转义特殊的正则表达式字符并可以分别跟踪多种引号:
function regex_escape($subject) {
return str_replace(array('\\', '^', '-', ']'), array('\\\\', '\\^', '\\-', '\\]'), $subject);
}
function quoted_explode($subject, $delimiters = ',', $quotes = '\'') {
$clauses[] = '[^'.regex_escape($delimiters.$quotes).']';
foreach(str_split($quotes) as $quote) {
$quote = regex_escape($quote);
$clauses[] = "[$quote][^$quote]*[$quote]";
}
$regex = '(?:'.implode('|', $clauses).')+';
preg_match_all('/'.str_replace('/', '\\/', $regex).'/', $subject, $matches);
return $matches[0];
}
(请注意,我将所有变量保留在方括号之间,以尽量减少需要转义的内容 - 在方括号之外,特殊字符的数量大约是两倍。)
如果您想使用 ] 作为引用,那么您可能想使用 [ 作为相应的引用,但我会将添加该功能作为练习留给读者。 :)