在论坛中的递归引用

kwi*_*chz 5 php regex forum recursion quote

我在一个用PHP编写的网站上为自己的个人论坛编写了一个引用函数.

引用标签的消息看起来像[quote=username]message[/quote],所以我写了这个函数:

$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);
Run Code Online (Sandbox Code Playgroud)

如果引用是一个,但是当用户引用引用时,这个不起作用,这不起作用.所以我需要一种递归引用来应用这种行为.

我试图搜索很多主题,但我真的不明白它是如何工作的.将不胜感激任何有关此类操作的建议/提示!让我知道,谢谢!

编辑

最后,这是我自己的解决方案:

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);
Run Code Online (Sandbox Code Playgroud)

只有在出现次数正确的情况下才能补充.所以它应该(对吧?)来防止html破坏或其他恶意攻击.你怎么看?

Mel*_*Mel 1

您只需将开始引号标记替换为开始 div 标记,对于结束部分也是如此。如果用户弄乱了引用标签匹配,这只会变得很糟糕。或者,您可以使用内部部分递归引用函数:

<?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);
}
?>
Run Code Online (Sandbox Code Playgroud)