Is there an opposite to strip_tags?

As title really, for example:

strip_tags($text, '<img>') //strips all tags other than the image tag

However, I need it to do the reverse i.e accept all tags, but strip any image tags from $text. If it existed the function might work something like this:

allow_tags($text, '<img>') //allows all tags, but strips image tags

Does such a function or something like it exist as I can’t find it. I’m at the planning stages of a mobile version of my site and thought that if I could strip images from my page content it would help things load faster for the user.

There isn’t as far as I know, you would have to write your own function to do that. Here is some weird function I found in my archive, maybe it can be of some use?

    function stripTagsAttributes($string, $allowedTags = null, $allowedAttributes = null) {
        if ($allowedAttributes) { 
            if (!is_array($allowedAttributes)) {
                $allowedAttributes = explode(',', $allowedAttributes);
            if (is_array($allowedAttributes)) {
                $allowedAttributes = implode('|', $allowedAttributes);
            $rep = '/([^>]*) (' . $allowedAttributes . ')(=)(\\'.*\\'|".*")/i';
            $string = preg_replace($rep, '$1 $2_-_-$4', $string); 
        if (preg_match('/([^>]*) (.*)(=\\'.*\\'|=".*")(.*)/i', $string) > 0) {
            $string = preg_replace('/([^>]*) (.*)(=\\'.*\\'|=".*")(.*)/i', '$1$4', $string);
        $rep = '/([^>]*) (' . $allowedAttributes . ')(_-_-)(\\'.*\\'|".*")/i';
        if ($allowedAttributes) {
            $string = preg_replace($rep, '$1 $2=$4', $string);
        return strip_tags($string, $allowedTags);

The strip_tags call accepts a parameter telling it specifically what to strip so it can do what you want.

Don’t rely on strip_atgs, it has a lot of security holes. I’d suggest that you take a look at HtmlPurifier

HTMLPurifier filters HTML, id doesn’t remove tags unless they are not valid in the doctype. Img tags inside a text is valid makrup so HTMLPurifier would not help him.

Which can also remove tags even valid tags. Do you not read the documentation?


I never used it for removing HTML tags. I learn something new every day.



HTML Purifier doesn’t solve his issue in the right manner.

Just use a regex.