通过preg_replace()交换所有网站网址以进行嵌入

时间:2014-06-19 16:23:23

标签: php regex filter preg-replace

我正在尝试用另一段文本替换我的代码中的url。

我有这样的网址

http://example.com/id/16028

我需要在我的过滤器代码中使用<h2>Not Allowed</h2>替换所有这些内容。

<a href="http://example.com/id/16028" rel="nofollow">http://example.com/id/16028</a>

所以这个文字

Hello here is my link <a href="http://example.com/id/16028" rel="nofollow">http://example.com/id/16028</a>

看起来像这样

Hello here is my link <h2>Not Allowed</h2>

我对正则表达式的态度非常糟糕这是我到目前为止所拥有的

function custom_filter($content){
    $rules = array(
        '#<a href="http://(www\.)?example\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?" rel="nofollow">http://(www\.)?example\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?</a>#i' => '<h2>Not Allowed</h2>',
        '#<a (?:.*?)href=["\\\']href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*example\.com\/id\/([^ ?\n/]+)((\?|/).*?(\n|\s))["\\\']#ixs' => '<h2>Not Allowed</h2>'

    );

    foreach ($rules as $link => $player)
        $content = preg_replace($link, $player, $content);


    return $content;

}

请帮忙

我几乎有这个功能,但我仍然得到网址和更改文字。

function change_tags($content = ''){
    preg_match_all("/example.com\/id\/([1-9.-_]+)/", $content, $matches);
    foreach ($matches[1] as $key => $value) {
         $content .= '<h2>Not Allowed</h2>';
    }   
    return $content;

}

1 个答案:

答案 0 :(得分:0)

我会选择下面的内容。我猜你试图阻止一些垃圾邮件。

$spam = 'Your Spam';
$spam = preg_replace( '~<a.+?href="http:\/\/example\.com\/id\/[0-9]+"[^>]*?>[^<]*?<\/a>~is', '<h2>Not allowed</h2>', $spam );

这将允许垃圾邮件的多样化。您还可以执行特定域:

$spam = 'Your Spam';
$spam = preg_replace( '~<a.+?href="http:\/\/(?:www.)?example\.com[^"]*?"[^>]*?>[^<]*?<\/a>~is', '<h2>Not allowed</h2>', $spam );