Take the 2-minute tour ×

Here is the line of code I have which works great:

$content = htmlspecialchars($_POST['content'], ENT_QUOTES);

But what I would like to do is allow only certain types of HTML code to pass through without getting converted. Here is the list of HTML code that I would like to have pass:

<pre> </pre>
<b> </b>
<em> </em>
<u> </u>
<ul> </ul>
<li> </li>
<ol> </ol>

And as I go, I would like to also be able to add in more HTML later as I think of it. Could someone help me modify the code above so that the specified list of HTML codes above can pass through without getting converted?

share|improve this question
Htmlspecialchars doesn't look at html, it looks at characters <, >, etc and escapes them. So you cannot do it with htmlspecialchars... maybe htmlpurifier? –  Esailija Oct 10 '12 at 12:54
You cannot. But you could convert constrained whitelisted tags back afterwards, &lt;em&gt; to <em> for example. –  mario Oct 10 '12 at 12:55

3 Answers 3

I suppose you could do it after the fact:

// $str is the result of htmlspecialchars()
preg_replace('#&lt;(/?(?:pre|b|em|u|ul|li|ol))&gt;#', '<\1>', $str);

It allows the encoded version of <xx> and </xx> where xx is in a controlled set of allowed tags.

share|improve this answer

Or you can go with old style:


$turned = array( '&lt;pre&gt;', '&lt;/pre&gt;', '&lt;b&gt;', '&lt;/b&gt;', '&lt;em&gt;', '&lt;/em&gt;', '&lt;u&gt;', '&lt;/u&gt;', '&lt;ul&gt;', '&lt;/ul&gt;', '&lt;li&gt;', '&lt;/li&gt;', '&lt;ol&gt;', '&lt;/ol&gt;' );
$turn_back = array( '<pre>', '</pre>', '<b>', '</b>', '<em>', '</em>', '<u>', '</u>', '<ul>', '</ul>', '<li>', '</li>', '<ol>', '</ol>' );

$content = str_replace( $turned, $turn_back, $content );
share|improve this answer
I think this (for a small amount of tags and content) could be actually much more faster :) –  jave.web Feb 17 at 9:00

You could use strip_tags

$exceptionString = '<pre>,</pre>,<b>,</b>,<em>,</em>,<u>,</u>,<ul>,</ul>,<li>,</li>,<ol>,</ol>';

$content = strip_tags($_POST['content'],$exceptionString );
share|improve this answer
That's not exactly what OP is asking for. –  Dainis Abols Oct 10 '12 at 13:03

Your Answer


