1

重複の可能性:
phpregex[b]から<b>

私は正規表現に問題があります、私は絶対的な正規表現の初心者です。HTMLを「BBCode」に変換しようとすると何が問題になっているのかわかりません。

誰かが「引用符で囲まれていない」関数を見て、私が犯している明らかな間違いを教えてもらえますか?(私は常に明白でないエラーを見つけるので、それは明らかです)

注:再帰的な正規表現を使用していないのは、頭を悩ませることができず、引用符をネストするためにこの方法で引用符を並べ替える作業をすでに開始しているためです。

<?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>

よろしくお願いします、サム。

4

2 に答える 2

3

さて、あなたはあなたのphpクラスをどちらかに設定することから始めることができますquote-titlequote_title、それを一貫性を保つようにしてください。

次に、2番目の関数にを追加する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>コードがある場合、引用符を外すと奇妙な動作が発生する可能性があります。

于 2012-10-07T22:23:47.850 に答える
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);

また、これを簡単にするために1つの正規表現として実行します。

'(\[quote=(.*?)\](.*?)\[/quote\])is'
'<div class="quote"><div class="quote-title">$1 wrote:</div><div class="quote-inner">$1</div></div>'
于 2012-10-07T22:31:27.630 に答える