gpt4 book ai didi

PHP 和正则表达式 : Split a string by commas that are not inside brackets (and also nested brackets)

转载 作者:可可西里 更新时间:2023-11-01 12:41:25 25 4
gpt4 key购买 nike

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

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

我要解析这个字符串:

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 中执行此操作。

提前致谢!

最佳答案

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

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

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

$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 和正则表达式 : Split a string by commas that are not inside brackets (and also nested brackets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1084764/

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