Question

i try to replace all img src that not contain full url with full image url

example like this

<?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>";

?>

and when replace became like this

 <?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>";

 ?>

so how to check every img src that not full link and replace it ? ( the $html_str is dynamic based on mysql )

please give me some solution for this problem

thanks

Was it helpful?

Solution

I'd do it properly using a DOM library, eg

$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);

Demo here - http://ideone.com/4K9pyD

OTHER TIPS

Try this:

You can get image source using following code:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

After that check string contains http or not. According do the operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top