Re: Keep HTML tags, but strip attributes

From: Date: Sat, 03 Apr 2004 22:08:46 +0000
Subject: Re: Keep HTML tags, but strip attributes
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-182260@lists.php.net to get a copy of this message
Matt Palermo wrote:
I am building a system which allows users to post data. I want to allow them to use ONLY certain tags such as <p>, </p>, <b>, </b>, <i>, </i>, etc... I want to allow them to use only these, and then strip out ALL attributes inside the tags. So if they input something like <p junk=junk>, it would switch it to just <p>. Anyone know of a way this can be done?
regular expressions, heres an example: <?php $input = 'this <div>is some</div> <u><b class="haxor">bad</b></u> HTML'; echo "{$input}\n"; $input = preg_replace('/<\/?[^pbiu\/][^>]*>/', '', $input); echo "{$input}\n"; $input = preg_replace('/<([pbiu])[^>]*>/', '<\1>', $input); echo "{$input}\n"; $input = str_replace('bad', 'good', $input); echo "{$input}\n"; ?> you might also think about stripping <script> tags etc. try taking a look at some forum code (e.g. phpbb.com) to see how they do it. no doubt that some real regexp wizard could perform the above replacements in a single regexp but hopefully it gives you an idea... if your not yet familiar with regexps then I strongly recommend you read the relevant part of the manual - they are very handy things indeed.
Thanks, Matt Palermo http://sweetphp.com


« previous php.general (#182260) next »