Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I use htmlspecialchars but allow only specific HTML code to pass through without getting converted?

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?

like image 364
Garry Avatar asked Oct 10 '12 12:10

Garry


1 Answers

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.

like image 59
Ja͢ck Avatar answered Oct 13 '22 22:10

Ja͢ck