sterling
sterling

Reputation: 625

Regular expression to remove <p> tags from around img elements

I am looking for a regex to convert all

<p><img /></p> 

to simply

<img />

The img tags will be fully populated such as

<img src="/file.jpg" width="1" height="2" />

Thank you for your input!

Upvotes: 1

Views: 3161

Answers (1)

jb.
jb.

Reputation: 10361

This will work if there is nothing else on the line except the three tags. Let me know if you want it explained further.

$str = "<p><img src=\"/file.jpg\" width=\"1\" height=\"2\" /></p>"
$replaced = preg_replace ( "/<p[^>]*?>(<img[^>]+>)<\/p>/" , "$1" , $str )

Upvotes: 2

Related Questions