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 :/

2
  • 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. Commented Nov 18, 2018 at 2:30
  • 1
    Please don't try to parse [X]HTML using regex. You may want to take a look at this. Commented Nov 18, 2018 at 3:05

1 Answer 1

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

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

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.