替换 <a> 的正则表达式与各自的 <img> [英] Regular expression to replace an <a> with respective <img>

查看:57
本文介绍了替换 <a> 的正则表达式与各自的 <img>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 PHP preg_replace() 解决方案来查找图像的链接并将它们替换为相应的图像标签.

I'm looking for a PHP preg_replace() solution find links to images and replace them with respective image tags.

查找:

<a href="http://www.domain.tld/any/valid/path/to/imagefile.ext">This will be ignored.</a>

替换为:

<img src="http://www.domain.tld/any/valid/path/to/imagefile.ext" alt="imagefile" />

其中协议必须是 http://,.ext 必须是有效的图像格式(.jpg、.jpeg、.gif、.png、.tif),并且基本文件名变为 alt=""价值.

Where the protocol MUST be http://, the .ext MUST be a valid image format (.jpg, .jpeg, .gif, .png, .tif), and the base file name becomes the alt="" value.

我知道 preg_replace() 是适合这项工作的函数,但我对正则表达式很不满意,所以非常感谢任何帮助!谢谢!

I know preg_replace() is the right function for the job, but I suck with regex, so any help is greatly appreciated! THANKS!

推荐答案

恭喜,你是问 Stack Overflow 如何用正则表达式解析 HTML 的百万分之一客户!

Congratulations, you are the one millionth customer to ask Stack Overflow how to parse HTML with regex!

[X][HT]ML 不是正则语言,不能用正则表达式可靠地解析.使用 HTML 解析器.PHP 本身为您提供 DOMDocument,或者您可能更喜欢 simplehtmldom.

[X][HT]ML is not a regular language and cannot reliably be parsed with regex. Use an HTML parser. PHP itself gives you DOMDocument, or you may prefer simplehtmldom.

顺便说一句,您无法通过查看其 URL 来判断文件的类型.JPEG 没有理由必须将.jpeg"作为其扩展名 — 并且实际上,不能保证带有.jpeg"扩展名的文件实际上是 JPEG.唯一确定的方法是获取资源(例如,使用 HEAD 请求)并查看 Content-Type 标头.

Incidentally, you cannot tell what type a file is by looking at its URL. There is no reason a JPEG has to have ‘.jpeg’ as its extension — and indeed, no guarantee that a file with ‘.jpeg’ extension will actually be JPEG. The only way to be certain is to fetch the resource (eg. using a HEAD request) and look at the Content-Type header.

这篇关于替换 &lt;a&gt; 的正则表达式与各自的 &lt;img&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆