This function simply converts HTML special characters to their HTML entities, while preserving already existing HTML entities. It uses the HTML translation table for the convertion.
So if you have a sentence including HTML special characters and HTML entities, it will be parsed as the HTML entities, so no markup will be performed.
<?php
/**
* htmlspecialchars2()
* Converts special characters to HTML entities
* Prereserves already existing HTML entities
* @param mixed $string string to be manipulated
* @param mixed $quote quote convertion style
* @return string $string
*/
function htmlspecialchars2($string, $quote = ENT_QUOTES){
if (!is_string($string))
return;
$specialchars = get_html_translation_table(HTML_SPECIALCHARS, $quote);
foreach ($specialchars as $char => $entitie)
if (preg_match("@{$entitie}@si", $string)){
$string = preg_replace("@{$entitie}@", $char, $string);
}
return strtr($string, $specialchars);
}
// Preserving HTML entities
echo htmlspecialchars2('<em>Italic!</em> <strong>Bold text!</strong> & <strong>Bold text again!</strong>');
echo "<br />\n";
// Original PHP
echo htmlspecialchars('<em>Italic!</em> <strong>Bold text!</strong> & <strong>Bold text again!</strong>');
?>
This is the output of the above snippet:
<em>Italic!</em> <strong>Bold text!</strong> & <strong>Bold text again!</strong>
<em>Italic!</em> <strong>Bold text!</strong> & <strong>Bold text again!</strong>
Mail this!
- Comments (0)
- PingBacks (0)
- TrackBacks (0)


» Latest comments