【问题标题】:PHP preg_replace multiple url replacesPHP preg_replace 多个 url 替换
【发布时间】:2014-05-07 16:31:29
【问题描述】:

嘿,我正在尝试做 2 个 preg_replace: 1.将所有网址制作成html链接 2.将所有图片的url转成html的img标签

但是这些正则表达式取消了另一个

<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = "!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.comhttp://www.ynet.co.il http://dogsm.files.wordpress.com/2011/12/d7a1d7a7d795d791d799-d793d795.jpg";

// Check if there is a url in the text
    $text = preg_replace($reg_exImg, '<img src=$0 >', $text);
    $text = preg_replace($reg_exUrl, '<a href="$0" rel="nofollow">$0</a>', $text);
    echo $text;
?>

我怎样才能让 preg_replace 使链接的 url 不对标签执行此操作?

谢谢。

海姆

【问题讨论】:

    标签: php regex preg-replace preg-match


    【解决方案1】:

    这可能作为回调更好。

    只使用$reg_exUrl,然后这样做:

    $text = preg_replace_callback($reg_exUrl,function($m) {
        if( preg_match("/\.(?:jpe?g|png|gif)$/i",$m[0])) {
            return "<img src='".$m[0]."' />";
        }
        else {
            return "<a href='".$m[0]."' rel='nofollow'>".$m[0]."</a>";
        }
    },$text);
    

    【讨论】:

    • 谢谢老兄(再次:))它的工作,你是最好的;)
    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 2014-07-12
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    相关资源
    最近更新 更多