在评论中查找图片网址并转换为img标记

时间:2011-10-30 12:09:58

标签: php regex image replace

有没有办法在评论中找到图片来源并将其转换为img代码?

我发现此代码可以找到一个URL并将其转换为链接:

$comment = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a rel=\"nofollow\" href=\"\\0\">\\0</a>", $comment);

但现在我想对图像做同样的事情。

如果我的评论如下:

This is an image http://localhost/website/image.gif

我希望它成为

This is an image <img src="http://localhost/website/image.gif" />

1 个答案:

答案 0 :(得分:2)

您需要在评论中找到所有网址,并将其用作基于扩展程序的链接或图片:     

$comment = "hi! its a link: http://www.google.com and this is image http://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Liliumbulbiferumflowertop.jpg/220px-Liliumbulbiferumflowertop.jpg  and this is ftp link ftp://domain.com/file.zip";
echo $comment."<br>-------------------------------------<br>";

$m = preg_match_all( "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", $comment, $match);

if ($m) {
    $links = $match[0];
    foreach($links as $link) {
        $extension = strtolower(trim(@end(explode(".",$link))));
        switch($extension) {
            case 'gif':
            case 'png':
            case 'jpg':
            case 'jpeg':
                $comment = str_replace($link, '<img src="'.$link.'">', $comment);       
                break;
            default:
                $comment = str_replace($link, '<a rel="nofollow" href="'.$link.'">'.$link.'</a>', $comment);
                break;
        }
    }
}

echo $comment."<br><br>";

DEMO: http://codepad.viper-7.com/d3T1Xw

它正在使用http,https,ftp,ftps