Convert HTML special characters to HTML entities preserving HTML entities

Views: 20 Last modified: August 04th, 2011 Comments: 0

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> & &lt;strong&gt;Bold text again!&lt;/strong&gt;');
echo "<br />\n";
// Original PHP
echo htmlspecialchars('<em>Italic!</em> <strong>Bold text!</strong> & &lt;strong&gt;Bold text again!&lt;/strong&gt;');
?>

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> & &lt;strong&gt;Bold text again!&lt;/strong&gt;

VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {5+6} =  
    Anything to add ?

        You must be logged in to post a comment.