删除图像周围的 <p> 个标签

remove <p> tags arround images

我有一个字符串:

$str = '<p>line</p>
        <p><img src="images/01.jpg">line with image</p>
        <p><img src="images/02.jpg">line with image</p>';

并想把它变成:

$str = '<p>line</p>
        <img src="images/01.jpg"><p>line with image</p>
        <img src="images/02.jpg"><p>line with image</p>';

我试过了

$result = preg_replace('%(.*?)<p>\s*(<img[^<]+?)\s*</p>(.*)%is', '', $str);

但它只删除了一张图片而不是第二张图片。请建议一个正则表达式。

这将从 img 周围删除 <p> 标签(使用 DOM 解析器)

    $html = str_get_html('<p>line</p>
            <p><img src="images/01.jpg">line with image</p>
            <p><img src="images/02.jpg">line with image</p>');


    foreach($html->find('img') as $img) {    
  $str ="<p>".$img->parent()->plaintext."</p>";
  $img->parent()->outertext=$img;
  $img->parent()->outertext .=$str;

}
echo $html;

o/p:

<p>line</p>          
<img src="images/01.jpg">
  line with image          
<img src="images/02.jpg">
  line with image

找到了我猜的解决方案。这两个正则表达式一起解决了我的问题:

$str = '<p>line</p>
        <p><img src="images/01.jpg">line with image</p>
        <p>line with image<img src="images/02.jpg"></p>';
$str = preg_replace('/<p>(<img[^>]*>)/', '<p>', $str);
$str = preg_replace('/(<img[^>]*>)<\/p>/', '</p>', $str);
echo $str;

o/p:

<p>line</p>          
<img src="images/01.jpg"><p>line with image</p>          
<p>line with image</p><img src="images/02.jpg">

这是工作 link 和 非常感谢大家,特别是@bobblebobble