正则表达式改变 <img>相对 URL 到绝对 URL [英] Regex to change <img> relative URLs to absolute
本文介绍了正则表达式改变 <img>相对 URL 到绝对 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要查看一串 HTML 并将所有 <img>
标签(其中 src
属性是相对地址)更改为绝对 URL.所以这个:
I need to look inside a string of HTML and change all <img>
tags where the src
attribute is a relative address, to an absolute URL. So this:
<img src="puppies.jpg">
需要变成:
<img src="http://sitename.com/path/puppies.jpg">
同时忽略 标签,其
src
属性已经是绝对的.
while ignoring <img>
tags whose src
attribute is already absolute.
我正在使用 PHP 并假设我需要通过 preg_replace()
运行它.帮助!谢谢!
I'm using PHP and assume that I'll need to run this through preg_replace()
. Help! And Thanks!
推荐答案
这不是正则表达式的工作.这是 XML/DOM 解析器的工作.
This is not a job for a regular expression. It's a job for an XML/DOM parser.
我想试试 DOMDocument.
I'd give DOMDocument a shot.
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$imgs = $DOM->getElementsByTagName('img');
foreach($imgs as $img){
$src = $img->getAttribute('src');
if(strpos($src, 'http://sitename.com/path/') !== 0){
$img->setAttribute('src', "http://sitename.com/path/$src");
}
}
$html = $DOM->saveHTML();
这篇关于正则表达式改变 <img>相对 URL 到绝对 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文