8
7

More than 5 years have passed since last update.

PHPで動的n次元配列追加をしたいです。 preg_replace_callbackで。

Last updated at Posted at 2016-02-13

PHPで動的n次元配列追加をしたいです。 例え… - Qiita

function parse($s)
{
    $a = null;
    while ($s = preg_replace_callback('/(\w*)\((\w*)\)/', function($matches) use (&$a) {
        list(, $k, $v) = $matches;
        $k = empty($k) ? 0 : $k;
        $a = empty($v) ? [$k => $a] : [$k => [$v]];
    }, $s));
    return $a;
}

assert(parse('a((b((c))))') === ['a' => [['b'=>[['c']]]]]);
assert(parse('(c)') === [['c']]);
assert(parse('b(c)') === ['b' => ['c']]);
function parse($s)
{
    $a = null;
    while ($s = preg_replace_callback('/(\w*)\((\w*)\)/', function($matches) use (&$a) {
        list(, $k, $v) = $matches;
        $a = array_values(array_filter(empty($v) ? [$k, $a] : [$k, [$v]]));
    }, $s));
    return $a;
}

assert(parse('a((b((c))))') === ['a', [['b', [['c']]]]]);
assert(parse('(c)') === [['c']]);
assert(parse('b(c)') === ['b', ['c']]);
8
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7