I have wrote a Quote function for my own personal forum, in a website written with PHP.
The message quoted tags looks like [quote=username]message[/quote]
, so I wrote that function :
$str=preg_replace('#\[quote=(.*?)\](.*?)\[/quote\]#is', '<div class="messageQuoted"><i><a href="index.php?explore=userview&userv=$1">$1</a> wrote :</i>$2</div>', $str);
This one works if the quote is one, but then a user quote a quote, this doesnt works. So I need a sort of recursive quote for apply this behaviour.
I tried to searching on SO many topics, but I don't really understand how it can works. Would be appreciated any suggestions/tips for do this kind of operation! Let me know, and thanks!
EDIT
At the end, this is my own solution :
if(preg_match_all('#\[quote=(.*?)\](.*?)#is', $str, $matches)==preg_match_all('#\[/quote\]#is', $str, $matches)) {
array_push($format_search, '#\[quote=(.*?)\](.*?)#is');
array_push($format_search, '#\[/quote\]#is');
array_push($format_replace, '<div class="messageQuoted"><a class="lblackb" href="index.php?explore=userview&userv=$1">$1</a> wrote :<br />$2');
array_push($format_replace, '</div>');
}
$str=preg_replace($format_search, $format_replace, $str);
it repleace only if the number of occurences is correct. So it should (right?) to prevent html broke or other malicious attack. What do you think?
PCRE and regexes in PHP do allow for recursion http://php.net/manual/en/regexp.reference.recursive.php - You will need the (?R)
syntax for that.
But it usually only matches recursively, it does not apply your replacement string recursively. Hencewhy you need to use preg_replace_callback
at the very least.
It's difficult to get working, but I believe (totally untested) this might do in your case:
= preg_replace_callback('#\[quote=(.*?)\]((?:(?R)|.*?)+)\[/quote\]#is',
'cb_bbcode_quote', $str);
Now the callback returns the wrapped content, after it has to invoke the same regex again on the $match[1] inner text, and preg_replace_callback-call itself.
You can simply replace the opening quote tag with the opening div tag and same for the closing section. This only goes bad if the user messes up it's quote tag matching. Alternatively you can recurse the quote function with the inner section:
<?php
function quote($str)
{
if( preg_match('#\[quote=.*?\](.*)\[/quote\]#i', $str) )
return quote(preg_replace('#\[quote=.*?\](.*)\[/quote\]#i', '$1', $str);
return preg_replace('#\[quote=.*?\](.*)\[/quote\]#', '<div blabla>$1</div>', $str);
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With