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

php:在某些情况下替换每个img src,php,mysql,image,preg-replace,Php,Mysql,Image,Preg Replace,我尝试用完整图像url替换所有不包含完整url的img src 像这样的例子 <?php $html_str = "<html> <body> Hi, this is the first image <img src='image/example.jpg' /> this is the second image

我尝试用完整图像url替换所有不包含完整url的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>";

 ?>

当它变成这样的时候

<?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并替换它呢?(基于mysql的$html_str是动态的)

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


谢谢

我会使用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);
此处演示-

尝试以下操作:

您可以使用以下代码获取图像源:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
之后,检查字符串是否包含
http
。根据需要做手术