import.html
的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));
目标:
最佳答案
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();
}