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

2021-12-28 00:00:00 regex split php preg-match-all

在 PHP 中,我有以下字符串:

In PHP I have the following string :

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

我需要将此字符串拆分为以下部分:

I need to split this string into the following parts:

AAA
BBB
(CCC,DDD)
'EEE'
'FFF,GGG'
('HHH','III')
(('JJJ','KKK'),LLL, (MMM,NNN))
OOO

我尝试了几个正则表达式,但找不到解决方案.有什么想法吗?

I tried several regexes, but couldn't find a solution. Any ideas?

更新

在处理格式错误的数据、转义引号等时,我认为使用正则表达式并不是最好的解决方案.

I've decided using regex is not really the best solution, when dealing with malformed data, escaped quotes, etc.

感谢这里提出的建议,我找到了一个使用解析的函数,我重新编写了它以满足我的需要.它可以处理不同类型的括号,分隔符和引号也是参数.

Thanks to suggestions made on here, I found a function that uses parsing, which I rewrote to suit my needs. It can handle different kind of brackets and the separator and quote are parameters as well.

 function explode_brackets($str, $separator=",", $leftbracket="(", $rightbracket=")", $quote="'", $ignore_escaped_quotes=true ) {

    $buffer = '';
    $stack = array();
    $depth = 0;
    $betweenquotes = false;
    $len = strlen($str);
    for ($i=0; $i<$len; $i++) {
      $previouschar = $char;
      $char = $str[$i];
      switch ($char) {
        case $separator:
          if (!$betweenquotes) {
            if (!$depth) {
              if ($buffer !== '') {
                $stack[] = $buffer;
                $buffer = '';
              }
              continue 2;
            }
          }
          break;
        case $quote:
          if ($ignore_escaped_quotes) {
            if ($previouschar!="\") {
              $betweenquotes = !$betweenquotes;
            }
          } else {
            $betweenquotes = !$betweenquotes;
          }
          break;
        case $leftbracket:
          if (!$betweenquotes) {
            $depth++;
          }
          break;
        case $rightbracket:
          if (!$betweenquotes) {
            if ($depth) {
              $depth--;
            } else {
              $stack[] = $buffer.$char;
              $buffer = '';
              continue 2;
            }
          }
          break;
        }
        $buffer .= $char;
    }
    if ($buffer !== '') {
      $stack[] = $buffer;
    }

    return $stack;
  }

推荐答案

代替 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

相关文章