【问题标题】:Swap all website urls to embed via preg_replace()通过 preg_replace() 交换所有网站 url 以嵌入
【发布时间】:2014-06-19 16:23:23
【问题描述】:

我正在尝试用另一段文本替换代码中的 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;

}

请帮忙

我几乎可以使用此功能,但我仍在获取 url 以及更改文本。

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;

}

【问题讨论】:

  • 您没有对$content 进行任何更改。将$content = preg_replace(...); 替换为$string = preg_replace(...);,看看是否有帮助。
  • 抱歉更新了,只是我复制粘贴

标签: php regex filter preg-replace


【解决方案1】:

我会选择以下内容。我猜你正在尝试阻止一些垃圾邮件。

$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 );

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 2021-11-17
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多