Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP htmlentities allow <b> and <i> only

Using htmlentities() is there a way I can set to allow only <b> and <i> to convert into bold and italic text? I know there was one way of doing this, but i have forgotten.

like image 433
Dylan Cross Avatar asked Apr 06 '12 01:04

Dylan Cross


People also ask

What's the difference between HTML entities () and htmlspecialchars ()?

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.

What is HTML entities () function?

The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().


2 Answers

It's pretty easy

<?php
$string = htmlentities($text);
$string = str_replace(array("&lt;i&gt;", "&lt;b&gt;", "&lt;/i&gt;", "&lt;/b&gt;"), array("<i>", "<b>", "</i>", "</b>"), $string);
like image 69
Martin. Avatar answered Oct 22 '22 22:10

Martin.


I use a helper function:

#   Sanitizer function - removes forbidden tags, including script tags
function strip_tags_attributes( $str, 
    $allowedTags = array('<a>','<b>','<blockquote>','<br>','<cite>','<code>','<del>','<div>','<em>','<ul>','<ol>','<li>','<dl>','<dt>','<dd>','<img>','<ins>','<u>','<q>','<h3>','<h4>','<h5>','<h6>','<samp>','<strong>','<sub>','<sup>','<p>','<table>','<tr>','<td>','<th>','<pre>','<span>'), 
    $disabledEvents = array('onclick','ondblclick','onkeydown','onkeypress','onkeyup','onload','onmousedown','onmousemove','onmouseout','onmouseover','onmouseup','onunload') )
{       
    if( empty($disabledEvents) ) {
        return strip_tags($str, implode('', $allowedTags));
    }
    return preg_replace('/<(.*?)>/ies', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabledEvents) . ")=[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($str, implode('', $allowedTags)));
}

For your example, remove everything except <b> and <i> from the $allowedTags array.

like image 39
Tieson T. Avatar answered Oct 22 '22 20:10

Tieson T.