php替换文件中img的所有src属性

Ing*_*dak 5 html php dom

我有这样的页面链接:

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">
Run Code Online (Sandbox Code Playgroud)

的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));
Run Code Online (Sandbox Code Playgroud)

目标:

我想替换import.html文件中元素的所有 src属性,并返回带有新图像链接的文件.我设法创建替换一个元素.img

如何编辑它来遍历整个文件并替换所有属性并返回新的import.html和替换src的?

Ama*_*ali 11

getElementsByTagName()方法将返回DOMNodeList包含所有匹配元素的对象.目前,您只需修改一个img标记.要替换所有img标记,只需使用以下命令循环遍历它们foreach:

function replace_img_src($img_tag) {
    $doc = new DOMDocument();
    $doc->loadHTML($img_tag);
    $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);
    }
    return $doc->saveHTML();
}
Run Code Online (Sandbox Code Playgroud)