简体   繁体   English

从 URL 创建 Img 标签

[英]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.如果字符串中的 URL 在 URL 的末尾(不是字符串)包含一个.jpg ,那么它应该使用preg_replace从中制作一个图像,否则制作一个普通链接。

so for example:所以例如:

If I have http://www.example.com/images/photo.jpg then it should replace with:如果我有http://www.example.com/images/photo.jpg那么它应该替换为:

<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 :( . URL 以任何方式替换为链接,我的正则表达式不起作用:(。

What I have tried:我尝试过的:


        $content = 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;
}

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 .在上图中,路由器 R1 有两个点对点。 '; ';

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

echo $parse_img;

Suyash苏亚什

$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.您可以将(?=\\.jpg)更改为(?<=\\.jpg)但还有其他更清晰的正则表达式,我相信其他人会发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM