More than 5 years have passed since last update.
@suin(suin@TypeScriptが好き)in👁 Image
Craftsman Software
Craftsman Software
PHPで動的n次元配列追加をしたいです。 preg_replace_callbackで。
8
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']]);
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
