我想获取存储在变量中的代码块,并替换其中任何图像标签的 src,而不干扰代码块的其余部分。
例如:代码块可能为:
<a href="http://mylink.com"><img src="image1.jpg"></a>
我想将其更改为(使用 PHP):
<a href="http://mylink.com"><img src="altimage.jpg"></a>
我目前正在使用我发现的解决方案,该解决方案使用 PHP DOM 模块来更改图像标签,但该函数仅返回更改后的 img 标签 HTML,而不返回其余的 HTML。
我调用的函数如下:
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->saveXML($tag);
}
return false;
}
当然,这只是返回更改后的 img 标签,但删除了其他 HTML(例如 A 标签) - 我将整个代码块传递给该函数。 (顺便说一句 - 对于没有图像标签的错误返回对我来说也是有好处的)。
请问我在这里缺少什么?
提前非常感谢您的帮助。
最佳答案
您需要使用return $doc->saveXML();
而不是return $doc->saveXML($tag);
。请参阅documentation saveXML:
saveXML ([ DOMNode $node [, int $options ]] )
node: Use this parameter to output only a specific node without XML declaration rather than the entire document.
关于php - 将 img src 替换为 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701514/