srromy
srromy

Reputation: 15

remove <p> tags arround images

I have a string:

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

and want to turn it into:

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

I tried

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

but it's only removing one image not the second one. Please suggest a regex.

Upvotes: 0

Views: 966

Answers (2)

srromy
srromy

Reputation: 15

found the solution I guess. these two regex together solves my problem:

$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[^>]*>)/', '$1<p>', $str);
$str = preg_replace('/(<img[^>]*>)<\/p>/', '</p>$1', $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">

here is the working link and thanks a lot every body and specially @bobblebobble

Upvotes: 0

B. Desai
B. Desai

Reputation: 16436

This will remove <p> tag from around img (using DOM parser)

    $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

Upvotes: 1

Related Questions