将图片网址转换为完整的html图片代码

时间:2013-09-27 05:13:34

标签: php

我正在处理评论事情,我希望我的用户能够发布图片网址,我将更改为带标记的图片网址

我的功能

function ImageTag($text) {
    // The Regular Expression filter
    $reg_exUrl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    // The Text you want to filter for urls
    if(preg_match_all($reg_exUrl, $text, $url)) {
           // make the urls hyper links
           $matches = array_unique($url[0]);
           foreach($matches as $match) {
                $check = substr($match, -4);
                if ($check == ".jpg" || $check == ".png" || $check == ".gif" || $check == "jpeg" || $check == ".JPG" || $check == ".PNG" || $check == ".GIF" || $check == "JPEG"){
                    $replacement = "<br/><img src=$match>";
                    $text = str_replace($match, $replacement, $text);
                }
           }
           return nl2br($text);
    } else {
           // if no urls in the text just return the text
           return nl2br($text);
    }
}

$text = "The text you want to filter goes here. <img src='http://static.php.net/www.php.net/images/php.gif'> http://www.facebook.com http://static.php.net/www.php.net/images/php.gif";
$content = ImageTag($text);
echo $content;

我完成了我的功能,但我不知道如何解决已经有html标签的图像

这就是我得到的

enter image description here

源代码:

The text you want to filter goes here. <img src="&lt;br/&gt;&lt;img src=http://static.php.net/www.php.net/images/php.gif&gt;"> http://www.facebook.com <br><img src="http://static.php.net/www.php.net/images/php.gif">

1 个答案:

答案 0 :(得分:0)

您可以首先解码html标记(htmlspecialchars_decode),然后剥离标记(strip_tags)并将'src ='替换为空白