1

これが私の状況です... vBulletin フォーラムに用語集アドオンをインストールしました。フォーラムで用語が見つかった場合、その用語は用語集の定義へのリンクに置き換えられます。

アドオンで使用される正規表現コードは次のとおりです。

$findotherterms[] = "#\b$glossaryname\b(?=\s|[.,?!;:]\s)#i";
$replacelinkterms[] = "<span class=\"glossarycrosslinkimage\"><a href=\"$glossarypath/glossary.php?do=viewglossary&amp;term=$glossaryid\"' onmouseover=\"glossary_ajax_showTooltip('$glossarypath/glossary_crosslinking.php?do=crosslink&term=$glossaryid',this,true);return false\" onmouseout=\"glossary_ajax_hideTooltip()\"><b>$glossaryname&nbsp;</b></a></span>";
$replacelinkterms[] = "<a href=\"glossary.php?q=$glossaryname\">$glossaryname</a>";
$glossaryterm = preg_replace($findotherterms, $replacelinkterms, $glossaryterm, $vbulletin->options['vbglossary_crosslinking_limit']);
return $glossaryterm;

問題は、既存の用語を含むフォーラム投稿内にリンクがある場合、アドオンがリンク内にリンクを作成することです...

それでは、「テスト」が用語集の用語であり、次のフォーラム投稿があるとしましょう。

some forum post including <a href="http://www.test.com">test</a> link

アドオンはそれを次のように変換します:

some forum post including <a href="http://www.<a href="glossary.php?q=test">test</a>.com"><a href="glossary.php?q=test">test</a> link

では、文字列が既存のリンク内にある場合、このコードを変更して何も置き換えないようにするにはどうすればよいですか?

4

1 に答える 1

3

説明

置き換えたくない悪い文字列を、置き換えたい良い文字列で実際にキャプチャしてから、いくつかのロジックを適用することをお勧めします。

この場合、正規表現は次のようになります。

  • <a ...>openから closeまでのすべてのアンカー タグを検索します</a>testこれは正規表現の最初にあるため、アンカー タグ内に存在する望ましくない文字列をすべてキャプチャします。
  • すべての文字列を検索します。この部分は、すべての用語集testの区切りリストに置き換えることができることに注意してください。|この値はキャプチャ グループ 1 に挿入されます。

/<a\b(?=\s)(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"\s]*)*"\s?>.*?<\/a>|(test)

ここに画像の説明を入力

次に、PHP ロジックは、キャプチャ グループ 1 が見つかったかどうかに基づいて、テキストを選択的に置き換えます。

PHP の例

実際の例: http://ideone.com/jpcqSR

コード

    $string = 'some forum test post including <a href="http://www.test.com">test</a> link';
    $regex = '/<a\b(?=\s) # capture the open tag
(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"\s]*)*"\s?> # get the entire tag
.*?<\/a>
|
(test)/imsx';

    $output = preg_replace_callback(
        $regex,
        function ($matches) {
            if (array_key_exists (1, $matches)) {
                return '<a href="glossary.php?q=' . $matches[1] . '">' . $matches[1] . '<\/a>';
            }
            return $matches[0];
        },
        $string
    );
    echo $output;

交換前

some forum test post including <a href="http://www.test.com">test</a> link

交換後

some forum <a href="glossary.php?q=test">test<\/a> post including <a href="http://www.test.com">test</a> link

于 2013-07-06T05:14:02.100 に答える