VOOZH about

URL: https://qiita.com/suin/items/ca05699cd03411ee4bdc

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


👁 Image
8

Go to list of users who liked

7

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@suin(suin@TypeScriptが好き)in👁 Image
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']]);
8

Go to list of users who liked

7
1

Go to list of comments

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

Go to list of users who liked

7