0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.