Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - replace <img> tags and return src

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.
like image 564
enloz Avatar asked Dec 09 '12 01:12

enloz


2 Answers

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();
like image 195
FtDRbwLXw6 Avatar answered Sep 29 '22 00:09

FtDRbwLXw6


$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;
like image 40
Prashant Tapase Avatar answered Sep 29 '22 00:09

Prashant Tapase