March 31, 2012

preg_replace script, link tag not working

Question by john

I used the following code to remove script, link tags from my string,

$contents='<script>inside tag</script>hfgkdhgjh<script>inside 2</script>';
$ss=preg_replace('#<script(.*?)>(.*?)</script>#is', '', $contents);
echo htmlspecialchars($ss);

it works fine. But can I use anything that similar to html parsing rather than preg_match for this?

Answer by Starx

Here are few things you can do

  1. htmlspecialchars() can prove those tags useless
  2. striptags() removes all HTML tags

But the technique you are using is the correct one. However here is a improved version for that

echo preg_replace('/<scriptb[^>]*>(.*?)</script>/is', "", $contents);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!