Question

Is it possible to us strip_tags to remove tags that are linking on an image?

For instance I want

<a href=""><img src="" /></a>

to be

<img src="" />

I need to keep the image and remove all a tags that are around them. Besides using Simple HTML Dom I was hoping there was an easier way to do this

Was it helpful?

Solution

You can't do it using strip_tags. You can use a regular expression instead:

$text = preg_replace("/<a[^>]+\>(<img[^>]+\>)<\/a>/i", '$1', $text);

This way is faster and much easier than Simple HTML Dom

OTHER TIPS

You can use regex to do it:

$string = '<a href=""><img src="" /></a>';
$string = preg_replace('/(<a(?: [^>]+| |)>)(?:[^<]+|)<img(?: [^>]+| |)>(?:[^<]+|)(<\/a>)/','$1$2',$string);

This should replace anything within a link if there is an <img> tag within it from within a link declaration as long as there are no other tags in between the link.

If you want to only replace the <img> tag portion under the same circumstances, you can use:

$string = '<a href=""><img src="" /></a>';
$string = preg_replace('/(<a(?: [^>]+| |)>)([^<]+|)<img(?: [^>]+| |)>([^<]+|)(<\/a>)/','$1$2$3$4',$string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top