将 img src 替换为 php

replace img src with php

我想获取存储在变量中的代码块,并在不影响代码块其余部分的情况下替换其中任何图像标签的 src。

例如:代码块可能显示为:

<a href="http://mylink.com"><img src="image1.jpg"></a>

我想将其更改为(使用 PHP):

<a href="http://mylink.com"><img src="altimage.jpg"></a>

我目前正在使用我发现的解决方案,它使用 PHP DOM 模块来更改图像标签,但函数 returns 只是更改了 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;
}

当然,这只是 return 更改后的 img 标签,但剥离了另一个 HTML(例如 A 标签)- 我将整个代码块传递给函数。 (顺便说一句 - 对于没有图像标签的假 return 对我来说也很好)。

请问我在这里遗漏了什么?

非常感谢您的帮助。

您需要使用 return $doc->saveXML(); 而不是 return $doc->saveXML($tag);。查看saveXML的documentation

saveXML ([ DOMNode $node [, int $options ]] )

node: Use this parameter to output only a specific node without XML declaration rather than the entire document.