0

I want to append a tag div before and after all tags img.

So I have

<img src=%random url image% />

And it should be replaced with

<div class="demo"><img src=%random url image% /></div>

Can I do it with preg_replace?

$string = %page source code%;
$find = array("/<img(.*?)\/>/");
$replace = array('<div class="demo">'.$find[0].'</div>');
$result = preg_replace($find, $replace, $string);

But it not work :/

Migu3litto
  • 81
  • 6
  • 3
    You _can_ probably do this with `preg_replace_, but that doesn't mean that you _should_ do it. Consider using an XML/HTML parser instead. – Tim Biegeleisen Nov 18 '18 at 02:30
  • 1
    Please don't try to parse [X]HTML using regex. You may want to take a look [at this](https://stackoverflow.com/a/1732454/5781745). – K.Dᴀᴠɪs Nov 18 '18 at 03:05

1 Answers1

2

A better way to parse HTML is using PHPs DOMDocument and DOMXPath classes. In your case, you can use XPath to find all the images, then add a div around them as shown in this example:

$html = '<div><img src="http://x.com" /><span>xyz</span><a href="http://example.com"><img src="http://example.com" /></a></div>';
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXpath($doc);
$images = $xpath->query('//img');
foreach ($images as $image) {
    $div = $doc->createElement('div');
    $div->setAttribute('class', 'demo');
    $image->parentNode->replaceChild($div, $image);
    $div->appendChild($image);
}
echo $doc->saveHTML();

Output:

<div>
    <div class="demo"><img src="http://x.com"></div>
    <span>xyz</span>
    <a href="http://example.com">
        <div class="demo"><img src="http://example.com"></div>
    </a>
</div>

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95