PHP - replace <img> tags and return src

13,576

Solution 1

This is the kind of problem that PHP's DOMDocument class excels at:

$dom = new DOMDocument();
$dom->loadHTML($content);

foreach ($dom->getElementsByTagName('img') as $img) {
    // put your replacement code here
}

$content = $dom->saveHTML();

Solution 2

$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;
Share:
13,576
enloz
Author by

enloz

Updated on July 18, 2022

Comments

  • enloz
    enloz almost 2 years

    Mission is to replace all <img> tags in given string with <div> tags and src property as inner text. In search for the answer I found similar question

    <?php
    
        $content = "this is something with an <img src=\"test.png\"/> in it.";
        $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
        echo $content;
    
    ?>
    

    result:

    this is something with an (image)  in it.
    

    Question: How to upgrade script ant get this result:

    this is something with an <div>test.png</div>  in it.
    
  • Jake
    Jake almost 10 years
    $img->setAttribute( 'src', $new_src_url );