note 46785 deleted from function.htmlentities by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 17:04:31 +0000 |
| Subject: | note 46785 deleted from function.htmlentities by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154934@lists.php.net to get a copy of this message | ||
Note Submitter: tmp1000 at fastmail dot deleteme dot fm
----
Regarding the two great function posted by pinkpather and webwurst; one to encode xml entities, the
other to encode only the entities of a string not already encoded. I've combined these two.
And IMHO made a small improvement by making the translation table static:
<?php
function xmlentities($string, $quote_style=ENT_QUOTES)
{
static $trans;
if (!isset($trans)) {
$trans = get_html_translation_table(HTML_ENTITIES, $quote_style);
foreach ($trans as $key => $value)
$trans[$key] = '&#'.ord($key).';';
// dont translate the '&' in case it is part of &xxx;
$trans[chr(38)] = '&';
}
// after the initial translation, _do_ map standalone '&' into '&'
return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&"
, strtr($string, $trans));
}
?>
Here's the snippet of code I'm testing with:
<?php
echo "<p>Testing xmlentities...</p>";
$strings[] = "No entities here.";
$strings[] = "<b>bold</b>";
$strings[] = "Got style? Try K & R.";
echo "<ul>";
foreach ($strings as $string) {
echo "<li>Original string: ".htmlentities($string)."</li>\n";
echo "<li>Encoded once:
".htmlentities(xmlentities($string))."</li>\n";
echo "<li>Encoded twice:
".htmlentities(xmlentities(xmlentities($string)))."</li>\n";
}
echo "</ul>";
?>