Skip to content

Instantly share code, notes, and snippets.

@hakre
Last active December 11, 2015 18:29
Show Gist options
  • Save hakre/4642090 to your computer and use it in GitHub Desktop.
Save hakre/4642090 to your computer and use it in GitHub Desktop.
Get nested bracket pairs from a string.
<?php
/**
* PHP: Algorithm for recursive string subset extraction
* @link http://stackoverflow.com/q/14532139/367456
* @link https://gist.github.com/4642090
* @link http://eval.in/7578
*/
$subject = 'abc{def}ghij{kl{mn}o{pq}}r{s{t{u{v}}w}}xyz';
$pattern = '([}{])';
$offset = 0;
$stack = [];
$accept = function($subject) {
echo $subject, "\n";
};
while (preg_match($pattern, $subject, $match, PREG_OFFSET_CAPTURE, $offset))
{
list($token, $position) = $match[0];
switch ($token)
{
# TOKEN_OPEN
case '{':
$stack[] = $position;
break;
# TOKEN_CLOSE
case '}':
$start = array_pop($stack);
$accept(substr($subject, $start + 1, $position - $start - 1));
break;
default:
throw new Exception(sprintf('Unexpected token "%s".', $token));
}
$offset = $position + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment