1

これは、stackoverflow の他の場所から取得して少し変更したコードの一部です。文字列内のすべてのリンクにクラスを追加します。

// adds class of ah_link to outbound links,
// This is intended as for use with tracking clicks on outbound links
private function add_tracking_link($html) {
    // no extra class on these websites!
    $follow_list = array($_SERVER['HTTP_HOST']);
    return preg_replace('%(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www\.)?'.implode('|(?:www\.)?',$follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>%', '$1$2$3"$4 class="ah_link ">',
        $html);
}

それはうまく機能しますが、クラスがすでに存在する場合、属性を2倍にするだけで問題が発生します。

既存のクラス属性に新しいクラス値を追加する方法があるかどうか疑問に思っていましたか? これは私の正規表現の安全地帯から抜け出しています。

4

1 に答える 1

1

最初に $html から class 属性を取り除き、追加の class 属性がないことを確認してから、正規表現を次のように実行します。

$out = preg_replace('/(<a[^>]*?)(class\s*\=\s*\"[^\"]*?\")([^>]*?>)/','$1$3',$html);
$return = preg_replace(<your regex here>,'<your replacement class here>',$out);

すなわち:

$out = preg_replace('/(<a[^>]*?)(class\s*\=\s*\"[^\"]*?\")([^>]*?>)/','$1$3',$html);
return preg_replace('%(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www.)?'.implode('|(?:www\.)?',$follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>%',
'$1$2$3"$4 class="ah_link ">',$out);
于 2012-05-30T15:06:19.090 に答える