简体   繁体   English

开闭 <p> 标签

[英]Closing and opening <p> tags

I have a function that wraps <img> tags in a <div> . 我有一个将<img>标记包装在<div>的函数。 Often these can appear in <p> tags (due to a wysiwyg editor). 通常,它们可以出现在<p>标记中(由于所见即所得的编辑器)。

    $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> . 我想更改我的功能,以便如果有一个打开的<p>标记,它会在该打开的<div>之前附加一个结束</p>标记,然后在结束</div>之后添加一个开头<p> </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> 而不是用<div>...</div>包装图像,而是用</p><div>...</div><p>包装图像
  2. detect the div tags and wrap them with </p>...<p> 检测div标签并用</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: 如果确定在图像周围使用的换行符始终<div>...</div>对,则可以考虑使用regex进行简单替换:

PHP 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. 如果在包装div元素中包含属性,这也将起作用。 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: 但是,如果您打算开始将regex用于HTML上的更复杂的操作,则以下是上一篇文章,其中详细介绍了为什么这样做不是一个好主意:

Using regular expressions to parse HTML: why not? 使用正则表达式解析HTML:为什么不呢?

You can use preg_replace function to achieve this. 您可以使用preg_replace函数来实现。

$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 我已经测试了几种情况,尽管使用其他几个进行了检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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