Thursday, January 10, 2013

PHP: Escape HTML output and allow custom html tags

Escape HTML output using htmlentities and allow at the same time a custom list of HTML tags.

 * Escape HTML output
 * Allow custom HTML tag list
 * @param string $sText
 * @return string
private function escapeHtml($sText)
    $sText = htmlentities($sText, ENT_QUOTES, 'UTF-8');
    $aAllowedTags = array('b', 'strong', 'i', 'em', 'br');
    foreach($aAllowedTags as $sTag)
        $sText = preg_replace('`&lt;(/?'.$sTag.'.*)&gt;`Ums', '<$1>', $sText);
    return $sText;

No comments: