Skip to content

Instantly share code, notes, and snippets.

@SleeplessByte
Last active December 11, 2015 23:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SleeplessByte/4674372 to your computer and use it in GitHub Desktop.
Save SleeplessByte/4674372 to your computer and use it in GitHub Desktop.
Matches nested tags such as [foo attr="data" loose ][foo]inner content[bar invisible="true"/][/foo][bar]lalala[/bar][/foo][foo]love[/foo] correctly. Simply recall on element->inner_content for recursive processing.
<?php
function regex_nested( $content ) {
$pattern = "/\[(?P<type>[^\]\s]+)(?P<props>[^\]]*?)((?P<tagclose>\s*\/\])|".
"(\](?P<inner>([^\[]*|\<\!\-\-.*?\-\-\>|(?R))*)\[\/\\1\s*\]))/sm";
if ( !preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE) )
return $content;
$elements = array();
foreach ( $matches[0] as $key => $match ) {
array_push( $elements, (object)array(
'node' => $match[0],
'type' => $matches['type'][$key][0],
'attributes_raw' => !empty( $matches['props'][$key][0] ) ? $matches['props'][$key][0] : '',
'attributes' => array(),
'no_inner' => (boolean)($matches['tagclose'][$key][1] > -1),
'inner_content' => !empty( $matches['inner'][$key][0] ) ? $matches['inner'][$key][0] : ''
) );
return $elements;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment