我尝试将所有不包含完整网址的img src替换为完整图片网址
像这样的例子<?php
$html_str = "<html>
<body>
Hi, this is the first image
<img src='image/example.jpg' />
this is the second image
<img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' />
and this is the last image
<img src='image/last.png' />
</body>
</html>";
?>
当替换变成这样的时候
<?php
$html_str = "<html>
<body>
Hi, this is the first image
<img src='http://example.com/image/example.jpg' />
this is the second image
<img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' />
and this is the last image
<img src='http://example.com/image/last.png' />
</body>
</html>";
?>
那么如何检查每个img src没有完整链接并替换它? ($ html_str是基于mysql的动态)
请给我一些解决这个问题的方法
感谢
答案 0 :(得分:2)
我正确使用DOM库,例如
$doc = new DOMDocument();
$doc->loadHTML($html_str);
$xp = new DOMXPath($doc);
$images = $xp->query('//img[not(starts-with(@src, "http:") or starts-with(@src, "https:") or starts-with(@src, "data:"))]');
foreach ($images as $img) {
$img->setAttribute('src',
'http://example.com/' . ltrim($img->getAttribute('src'), '/'));
}
$html = $doc->saveHTML($doc->documentElement);
在这里演示 - http://ideone.com/4K9pyD
答案 1 :(得分:0)
试试这个:
您可以使用以下代码获取图像源:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
之后,检查字符串是否包含http
。据操作说。