开发者

Create Img tag from URL

What I want


If the URL in the string contains a .jpg at the end of the URL (not the string) then it should make an image from it with preg_replace else make a normal link.

so for example:

If I have http://www.example.com/images/photo.jpg then it should replace with:

<img src="http://www.example.com/images/photo.jpg" alt="http://www.example.com/images/photo.jpg">

The problem:


The URL is replaced with a link in any way and my regex isn't working :( .

What I have tried:


        $conten开发者_开发问答t = preg_replace("/(http:\/\/[^\s]+(?=\.jpg))/i","<img src=\"$1\" alt = \"$1\"></img>",$content);    

        $content = nl2br(preg_replace("/(http:\/\/[^\s]+(?!\.jpg))/m", "<a href=\"$1\" rel=\"nofollow\" target=\"blank\" title=\"$1\" class=\"news-link\">$1</a>", $content));


Try this

function replace_links($content)
{
    if (preg_match('#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i', $content))
    {
        $content = preg_replace('#(http://[^\s]+(?=\.(jpe?g|png|gif)))(\.(jpe?g|png|gif))#i', '<img src="$1.$2" alt="$1.$2" />', $content);
    }
    else
    {
        $content = preg_replace('#(http://[^\s]+(?!\.(jpe?g|png|gif)))#i', '<a href="$1" rel="nofollow" target="blank" title="$1" class="news-link">$1</a>', $content);
    }

    return $content;
}


$content = preg_replace('#\b(http://\S+\.jpg)\b#i', '<img src="$1" alt="$1" />', $content);


You don't need lookaround. Just go with

$content = preg_replace("#(http://[^ ]+\\.jpg(?= |$)#i","<img src=\"$1\" alt=\"$1\"/>", $content);    


I think you used the lookahead operator when you wanted lookbehind. You could change (?=\.jpg) to (?<=\.jpg) but there are other, cleaner regex's I'm sure others will post.


This worked for me.

$parse_img='Hello, http://orbitco-ccna-pastquestions.com/images/Q5.jpg

In the figure above, router R1 has two point-to-point . ';

$parse_img=preg_replace('/(https?:\/\/(.\*)?\\.jpg|png|gif)[\s+]*/i',"< img src=\"$1\" alt = \"$1\">< /img >",$parse_img);

echo $parse_img;

Suyash

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜