PCRE and perl have built in recursive abilities see http://php.net/manual/en/regexp.reference.recursive.php. Finding information on recursion or examples of it has been rather difficult to track down, but I was able to get this one from the kind people at regexadvice.com
Code:
<?php
$text = '[one]text [two]text [three]text[/thre] text[/two] text[/one]';
$regexp = '{((\[([^\]]+)\])((?:(?:(?!\[/?\3\]).)*+|(?1))*)(\[/\3\]))}si';
while(preg_match($regexp,$text,$match)){
$text = preg_replace($regexp,'<$3>$4</$3>',$text);
}
echo $text;
?>
The above is something that will convert certain bbcode to html code. In this case
Code:
[one]text [two]text [three]text[/thre] text[/two] text[/one]
is converted to
Code:
<one>text <two>text [three]text[/thre] text</two> text</one>
notice that the mismatched bbcode was ignored.
It was also around this time that regex was making my head hurt so I stopped reading up on it. As I recall, this PCRE example still needs a touch of work, but for me should be a perfect example for experimenting with recursion later on when the desire/need arises to investigate this aspect of PCRE. I do not recall if/what/where this pattern failed, but yeah, it is beyond my understanding of PCRE.
On a side note, the script above looks like it should make sense, I have an understanding of all the terms, but with all the nested loops and different types going on in the PCRE given above it just makes my head hurt. It is like the feeling you get when you look at a card table covered with the 5000 pieces to a jigsaw puzzle! Sometimes it's best just to shove the pieces back into the box and put it away for a year or three.
Bookmarks