Jump to content

Stripping Tags


Arty Ziff

Recommended Posts

It seems like there should be a dedicated php function to strip a SPECIFIC tag, rather than the functionality of strip_tags.

 

I'm using this:

function stripSingleTags($tags, $string)

{

    foreach( $tags as $tag )

    {

        $string = preg_replace('#</?'.$tag.'[^>]*>#is', '', $string);

    }

    return $string;

}

But this will not help me if for example I want to trip out scripts <script> ... </script>.

 

Is there a better way?

Link to comment
Share on other sites

Well, if you take a look at the documentation of strip_tags(), then you'd see:

 

string strip_tags ( string $str [, string $allowable_tags ] )

 

You can pass an string of the allowed tags that it will leave unaffected. This is the simplest way to have the function, as you would much rather have a whitelist then a blacklist. Blacklisting requires constant updating, and the list of tags would be very long. Here's an example:

 

echo strip_tags("<p><script>alert('Hello World');</script>I don't like <a href='#'>Javascript</a></p><ul><li>This is a list.</li></ul>", "<p><a>");

Would output:

 

<p>I don't like <a href='#'>Javascript</a></p>
Link to comment
Share on other sites

Thanks, Mattal999, sure I thought about that, but out of the huge number of possible tags, it seems like there should be a better way that involved only listing the ones you DON'T want.

 

As to regex, I suppose that's the ideal way barring a native function...

 

THANKS!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.