[英]PHP: Find images and links with relative path in output and convert them to absolute path
[英]PHP - find and convert all links and images to display them in HTML
我看过很多与此相关的主题,但找不到适用于链接和图像的内容。
在我的 PHP 页面上,我回显 $content,其中包含来自我的数据库的记录。 在这个字符串中,可以有网址和图片网址。 我需要的是一个自动查找这些 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 等
转换您的项目(图像和链接)的一种方法是首先应用更具体的模式,然后在其他模式中对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上查看演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.