简体   繁体   中英

Closing and opening <p> tags

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:

  1. instead of wrapping images with <div>...</div> , wrap them with </p><div>...</div><p>
  2. detect the div tags and wrap them with </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:

Using regular expressions to parse HTML: why not?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM