更新时间:2023-11-18 15:15:22
这就是我想到的。它使用PHP DOM API创建一个小型的HTML文档,然后将XML保存为IMG元素。
$ b
This is what I've come up with. It uses the PHP DOM API to create a tiny HTML document, then saves the XML for just the IMG element.
function replace_img_src($original_img_tag, $new_src_url) {
$doc = new DOMDocument();
$doc->loadHTML($original_img_tag);
$tags = $doc->getElementsByTagName('img');
if(count($tags) > 0)
{
$tag = $tags->item(0);
$tag->setAttribute('src', $new_src_url);
return $doc->saveHTML($tag);
}
return false;
}
注意:5.3之前版本的PHP。 6, $ doc-> saveHTML($ tag)
可以更改为 $ doc-> saveXML($ tag)
。
Note: In versions of PHP before 5.3.6, $doc->saveHTML($tag)
can be changed to $doc->saveXML($tag)
.