PHP 和 RegEx:用不在括号内(以及嵌套括号)的逗号分割字符串 [英] PHP and RegEx: Split a string by commas that are not inside brackets (and also nested brackets)

查看:30
本文介绍了PHP 和 RegEx:用不在括号内(以及嵌套括号)的逗号分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两天前,我开始研究代码解析器,但遇到了困难.

Two days ago I started working on a code parser and I'm stuck.

如何用不在括号内的逗号分割字符串,让我告诉你我的意思:

How can I split a string by commas that are not inside brackets, let me show you what I mean:

我要解析这个字符串:

one, two, three, (four, (five, six), (ten)), seven

我想得到这个结果:

array(
 "one"; 
 "two"; 
 "three"; 
 "(four, (five, six), (ten))"; 
 "seven"
)

但我得到:

array(
  "one"; 
  "two"; 
  "three"; 
  "(four"; 
  "(five"; 
  "six)"; 
  "(ten))";
  "seven"
)

如何在 PHP RegEx 中执行此操作.

How can I do this in PHP RegEx.

先谢谢你!

推荐答案

您可以更轻松地做到这一点:

You can do that easier:

preg_match_all('/[^(,s]+|([^)]+)/', $str, $matches)

但是如果您使用真正的解析器会更好.也许是这样的:

But it would be better if you use a real parser. Maybe something like this:

$str = 'one, two, three, (four, (five, six), (ten)), seven';
$buffer = '';
$stack = array();
$depth = 0;
$len = strlen($str);
for ($i=0; $i<$len; $i++) {
    $char = $str[$i];
    switch ($char) {
    case '(':
        $depth++;
        break;
    case ',':
        if (!$depth) {
            if ($buffer !== '') {
                $stack[] = $buffer;
                $buffer = '';
            }
            continue 2;
        }
        break;
    case ' ':
        if (!$depth) {
            continue 2;
        }
        break;
    case ')':
        if ($depth) {
            $depth--;
        } else {
            $stack[] = $buffer.$char;
            $buffer = '';
            continue 2;
        }
        break;
    }
    $buffer .= $char;
}
if ($buffer !== '') {
    $stack[] = $buffer;
}
var_dump($stack);

这篇关于PHP 和 RegEx:用不在括号内(以及嵌套括号)的逗号分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆