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

标签 php html regex function

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

在我的 PHP 页面上,我回显 $content,其中包含来 self 的数据库的记录。在这个字符串中,可以有url和图片url。我需要的是一个可以自动找到这些 url 并以适当的 HTML 显示它们的功能。所以正常的链接应该显示为<a ...>....</a>和图像链接(以 jpeg、jpg、png、gif 等结尾)应显示为 <img ...> .

这是我仅针对 url 网站链接找到的内容:

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

echo $content; 

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

编辑:

http://example.com , https://example.com都应显示为 <a href="url">url</a> .所有不是图片的网址;

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

关于PHP - 查找并转换所有链接和图像以在 HTML 中显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976527/

相关文章:

PHP Regex preg_match提取

php - Laravel Livewire : load livewire component with button click

javascript - 在 url 中隐藏获取变量?

php - 如何在 MySQL 数据库中存储 JSON 字符串

javascript - 如何知道在一组动态生成的选项卡中选择并激活了哪个选项卡

html - 出现在同一背景图像下的下一页的标题

php - 文本区域中的换行符

regex - 如何使用多个工作线程处理logstash中的多行?

javascript - 如何从数据库获取图像 URL,以便当有人单击图像时他/她可以重定向到该 URL

sql - TSQL使用正则表达式提取字符串的一部分