I have a function that wraps <img>
tags in a <div>
. Often these can appear in <p>
tags (due to a wysiwyg editor).
$doc->loadHtml($str);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$div = $doc->createElement('div');
$tag->parentNode->insertBefore($div, $tag);
$div->appendChild($tag);
}
I want to change my function so that if there is an open <p>
tag, it appends a closing </p>
tag before the opening <div>
, and then adds an opening <p>
after the closing </div>
.
Currently when input is
'<p>blah blah <img src="incorrect.gif"> blah blah</p>
My output is
'<p>blah blah <div><img src="incorrect.gif"></div> blah blah</p>
I want output to be
'<p>blah blah </p><div><img src="correct.gif"></div><p> blah blah</p>
There are two approaches coming to my mind:
<div>...</div>
, wrap them with </p><div>...</div><p>
</p>...<p>
If you are certain that the wrapping you use around images is always a <div>...</div>
pair, you might consider using regex to do a simple replace:
PHP
$html = preg_replace_all('/<div[^>]*>(.*?)</div>/i', '</p>$1<p>', $html)
This will also work if you include attributes in your wrapping div
elements. However, if you intend on starting to use regex for more complex operations on HTML, here is a previous post that details why it is a bad idea:
You can use preg_replace function to achieve this.
$html ='<p>blah blah <div><img src="incorrect.gif"></div> blah blah</p>';
echo preg_replace("/<p>(.*?)<div>(.*?)<\/div>(.*?)<\/p>/", "<p>$1</p><div>$2</div><p>$3</p>", $html);
I have tested couple of case although check using couple others
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.