2012-10-07 22 views
1

可能重复:
php regex [b] to <b>正则表达式嵌套论坛报价(BB代码)

我在使用正则表达式麻烦

,我是一个绝对的正则表达式的小白。我无法看到尝试将HTML转换回“BBCode”时发生了什么问题。

有人可以看看'unquote'函数,并告诉我我正在犯的明显错误吗? (我知道这很明显,因为我总是发现不明显的错误)

注意:我没有使用递归正则表达式,因为我无法得到我的头,并且已经开始这种方式来整理行情他们嵌套。

<?php 
function quote($str){ 
    $str = preg_replace('@\[(?i)quote=(.*?)\](.*?)@si', '<div class="quote"><div class="quote-title">\\1 wrote:</div><div class="quote-inner">\\2', $str); 
    $str = preg_replace('@\[/(?i)quote\]@si', '</div></div>', $str); 
    return $str; 
} 

function unquote($str){ 
    $str = preg_replace('@\<(?i)div class="quote"\>\<(?i)div class="quote_title"\>(.*?)wrote:\</(?i)div\><(?i)div class="quote-inner"\>(.*?)@si', '[quote=\\1]\\2', $str); 
    $str = preg_replace('@\</(?i)div\></(?i)div\>@si', '[/quote]', $str); 
} 
?> 

这仅仅是一些代码,以帮助测试:

<html> 
<head> 
    <style> 
    body { 
     font-family: sans-serif; 
    } 
    .quote { 
     background: rgba(51,153,204,0.4) url(../img/diag_1px.png); 
     border: 1px solid rgba(116,116,116,0.36); 
     padding: 5px; 
    } 

    .quote-title, .quote_title { 
     font-size: 18px; 
     margin: 5px; 
    } 

    .quote-inner { 
     margin: 10px; 
    } 
    </style> 
</head> 
<body> 
    <?php 
    $quote_text = '[quote=VCMG][quote=2xAA]DO RECURSIVE QUOTES WORK?[/quote]I have no idea.[/quote]'; 
    $quoted = quote($quote_text); 
    echo $quoted.'<br><br>'.unquote($quoted); ?> 
</body> 

提前,山姆感谢。

回答

3

嗯,你可以通过PHP类设置你要么quote-titlequote_title但保持一致的开始。

然后,添加一个return $str;到你的第二个功能,你应该几乎在那里。

而且可以简化您的正则表达式是一个小:

function quote($str){ 
    $str = preg_replace('@\[quote=(.*)\]@siU', '<div class="quote"><div class="quote-title">\\1 wrote:</div><div class="quote-inner">', $str); 
    $str = preg_replace('@\[/quote\]@si', '</div></div>', $str); 
    return $str; 
} 

function unquote($str){ 
    $str = preg_replace('@<div class="quote"><div class="quote-title">(.*) wrote:</div><div class="quote-inner">@siU', '[quote=\\1]', $str); 
    $str = preg_replace('@</div></div>@si', '[/quote]', $str); 
    return $str; 
} 

,但不同的呼叫开始和你的报价结束标记,更换的提防。如果你碰巧有其他的bbcode创建</div></div>的代码,我简单地说,无引号会产生一些奇怪的行为。

+0

> _>该死的回报......我知道这是明显的东西。 并感谢您的简化,好多了! – 2xAA

0

就个人而言,我利用的事实,即所产生的HTML基本上是:

<div class="quote">Blah <div class="quote">INCEPTION!</div> More blah</div> 

反复运行的正则表达式,直到没有更多的匹配:

do { 
    $str = preg_replace(REGEX , REPLACE , $str , -1 , $c); 
} while($c > 0); 

而且,这样做的一个正则表达式使这更容易:

'(\[quote=(.*?)\](.*?)\[/quote\])is' 
'<div class="quote"><div class="quote-title">$1 wrote:</div><div class="quote-inner">$1</div></div>' 
+0

我认为读了一些使用量词的问号“反转贪婪”的地方,它不会简单地让他们变得懒惰。所以,如果因为使用了U选项而导致量词懒惰,那么使用'。*?'使它们再次变得贪婪,这不是你想要的。 – Cimbali

+0

啊,是的。我认为U是“unicode”,但这是小写的“u”。好的,会编辑。 –