note 46785 added to function.htmlentities
| From: | tmp1000 at fastmail dot deleteme dot fm | Date: | Sat, 23 Oct 2004 05:07:53 +0000 |
| Subject: | note 46785 added to function.htmlentities | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-78981@lists.php.net to get a copy of this message | ||
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>";
?>
----
Manual Page -- http://www.php.net/manual/en/function.htmlentities.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+46785
Delete -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46785&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+46785&report=yes
Search -- http://master.php.net/manage/user-notes.php