我有这样的页面链接:
import.html
<h1>Title</h1>
<img src="img/pic1.jpg" alt="" title="Picture 1" class="pic">
<img src="img/pic2.jpg" alt="" title="Picture 2" class="pic">
<img src="img/pic3.jpg" alt="" title="Picture 3" class="pic">
<p>random text</p>
<img src="img/pic4.jpg" alt="" title="Picture 4" class="pic">
index.php
<?php
//get file content
$html = file_get_contents('import.html');
function replace_img_src($img_tag) {
$doc = new DOMDocument();
$doc->loadHTML($img_tag);
$tags = $doc->getElementsByTagName('img');
if (count($tags) > 0) {
$tag = $tags->item(0);
$old_src = $tag->getAttribute('src');
$new_src_url = 'website.com/assets/'.$old_src;
$tag->setAttribute('src', $new_src_url);
return $doc->saveHTML($tag);
}
return false;
}
// usage
$new = replace_img_src($html);
print_r(htmlspecialchars($new));
目标:
我想用新的图像链接替换import.html文件和返回文件中src
元素的[[all img
属性]。我设法创建一个替换元素。
src
替换return new import.html
?>>标题
< img src =“ img / pic2.jpg” alt =“” title =“图片2” class =“ ...”>getElementsByTagName()
方法将返回一个包含所有匹配元素的getElementsByTagName()
对象。目前,您只修改了一个DOMNodeList
标签。要替换所有img
标签,只需使用img
遍历它们即可:$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$old_src = $tag->getAttribute('src');
$new_src_url = 'website.com/assets/'.$old_src;
$tag->setAttribute('src', $new_src_url);
$doc->saveHTML($tag);
}