PHP-查找并转换所有链接和图像,以HTML形式显示它们


PHP - find and convert all links and images to display them in HTML

我看过很多与此相关的主题,但找不到适用于链接和图像的内容。

在我的PHP页面上,我回显$content,其中包含我的数据库中的一条记录。在这个字符串中,可以有url和图像url。我需要的是一个自动查找这些url并以正确的HTML显示它们的函数。因此,正常链接应显示为<a ...>....</a>,图像链接(以jpeg、jpg、png、gif…结尾)应显示为<img ...>

这是我发现的网址网站链接只有:

$content = preg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
                        "<a href='"''0'">''0</a>", 
                        $content);
echo $content; 

我想我应该为此使用一些正则表达式代码,但我对此并不太熟悉。非常感谢!

编辑:

http://example.com,https://example.com应该都像CCD_ 3一样显示。所有不是图像的url;

http://www.example.com/image.png应显示为<img src="http://www.example.com/image.png">这适用于所有以png、jpeg、gif等图像扩展名结尾的URL。

对两个项目(图像和链接)进行转换的一种方法是首先应用更具体的模式,然后在其他模式中对src='使用负面的查找:

<?php
$content = "I am an image (http://example.com/image.png) and here's another one: https://www.google.com/image1.gif. I want to be transformed to a proper link: http://www.google.com";
$regex_images = '~https?://'S+?(?:png|gif|jpe?g)~';
$regex_links = '~
                (?<!src='') # negative lookbehind (no src='' allowed!)
                https?://   # http:// or https://
                'S+         # anything not a whitespace
                'b          # a word boundary
                ~x';        # verbose modifier for these explanations
$content = preg_replace($regex_images, "<img src='''0'>", $content);
$content = preg_replace($regex_links, "<a href='''0'>''0</a>", $content);
echo $content;
# I am an image (<img src='http://example.com/image.png'>) and here's another one: <img src='https://www.google.com/image1.gif'>. I want to be transformed to a proper link: <a href='http://www.google.com'>http://www.google.com</a>
?>

查看ideone.com

上的演示