gpt4 book ai didi

php:在某些情况下替换每个img src

转载 作者:行者123 更新时间:2023-11-29 08:05:00 25 4
gpt4 key购买 nike

我尝试用完整图像网址替换所有不包含完整网址的 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动态的)

请给我一些解决这个问题的方法

谢谢

最佳答案

我会使用 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

关于php:在某些情况下替换每个img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22904756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com