且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:在逗号上拆分字符串,但不在大括号或引号之间?

更新时间:2022-12-27 20:09:04

代替 preg_split,做一个 preg_match_all:

$str = "AAA, BBB, (CCC,DDD), 'EEE', 'FFF,GGG', ('HHH','III'), (('JJJ','KKK'), LLL, (MMM,NNN)) , OOO"; 

preg_match_all("/((?:[^()]|(?R))+)|'[^']*'|[^(),s]+/", $str, $matches);

print_r($matches);

将打印:

Array
(
    [0] => Array
        (
            [0] => AAA
            [1] => BBB
            [2] => (CCC,DDD)
            [3] => 'EEE'
            [4] => 'FFF,GGG'
            [5] => ('HHH','III')
            [6] => (('JJJ','KKK'), LLL, (MMM,NNN))
            [7] => OOO
        )

)

正则表达式 ((?:[^()]|(?R))+)|'[^']*'|[^(),s]+ 可以分为三部分:

The regex ((?:[^()]|(?R))+)|'[^']*'|[^(),s]+ can be divided in three parts:

  1. ((?:[^()]|(?R))+),匹配括号的平衡对
  2. '[^']*' 匹配一个带引号的字符串
  3. [^(),s]+ 匹配任何不包含 '(', ')' 的字符序列,',' 或空白字符
  1. ((?:[^()]|(?R))+), which matches balanced pairs of parenthesis
  2. '[^']*' matching a quoted string
  3. [^(),s]+ which matches any char-sequence not consisting of '(', ')', ',' or white-space chars