我来到这里时遇到了与此类似的复杂字符串拆分问题,但这里没有一个答案完全符合我的要求 - 所以我自己写了。
我在这里发布它以防万一它对其他人有帮助。
这可能是一种非常缓慢且低效的方法 - 但它对我有用。
function explode_adv($openers, $closers, $togglers, $delimiters, $str)
{
$chars = str_split($str);
$parts = [];
$nextpart = "";
$toggle_states = array_fill_keys($togglers, false); // true = now inside, false = now outside
$depth = 0;
foreach($chars as $char)
{
if(in_array($char, $openers))
$depth++;
elseif(in_array($char, $closers))
$depth--;
elseif(in_array($char, $togglers))
{
if($toggle_states[$char])
$depth--; // we are inside a toggle block, leave it and decrease the depth
else
// we are outside a toggle block, enter it and increase the depth
$depth++;
// invert the toggle block state
$toggle_states[$char] = !$toggle_states[$char];
}
else
$nextpart .= $char;
if($depth < 0) $depth = 0;
if(in_array($char, $delimiters) &&
$depth == 0 &&
!in_array($char, $closers))
{
$parts[] = substr($nextpart, 0, -1);
$nextpart = "";
}
}
if(strlen($nextpart) > 0)
$parts[] = $nextpart;
return $parts;
}
用法如下。explode_adv
接受 5 个参数:
- 打开一个块的字符数组 - 例如
[
,(
等。
- 关闭块的字符数组 - 例如
]
,)
等。
- 切换块的字符数组 - 例如
"
,'
等。
- 应该导致拆分为下一部分的字符数组。
- 要处理的字符串。
这种方法可能有缺陷 - 欢迎编辑。