How does this code work?
| From: | Robert Williams | Date: | Tue, 03 Jul 2012 02:15:12 +0000 |
| Subject: | How does this code work? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-318381@lists.php.net to get a copy of this message | ||
I found this code in a user comment in the PHP docs for htmlentities():
<?php
function xml_character_encode($string, $trans='') {
$trans = (is_array($trans)) ? $trans : get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
foreach ($trans as $k=>$v)
$trans[$k]= "&#".ord($k).";";
return strtr($string, $trans);
}
?>
It seems to work. For instance, this (assuming UTF-8 encoding):
echo xml_character_encode('Château');
echo "\n";
echo xml_character_encode('Ch&teau');
Yields this:
Château
Ch&teau
My question is, *how* does it work? It makes sense right up to the return statement. According to
the docs for strstr(), when a non-string is passed in as the needle, it's, "converted to
an integer and applied as the ordinal value of a character." First, an array-to-int conversion
is undefined, though it seems to produce 1 on my copy of PHP. Now, I'm not quite sure how to
interpret the last part of that statement from the docs, but I take it that the ultimate value
supplied to strstr() is going to be either '1' (the character value of the integer value
of the array) or '49' (the ordinal value of the character '1'). Whatever,
neither one makes sense to look for in the haystack, so I'm obviously missing something.
Perhaps it's just late-Monday slowness on my part, but what's going on here? I have no
intention of using this code, but I'd sure like to understand how it works!
Regards,
Bob
--
Robert E. Williams, Jr.
Associate Vice President of Software Development
Newtek Businesss Services, Inc. -- The Small Business Authority
https://www.newtekreferrals.com/rewjr
http://www.thesba.com/
________________________________
Notice: This communication, including attachments, may contain information that is confidential. It
constitutes non-public information intended to be conveyed only to the designated recipient(s). If
the reader or recipient of this communication is not the intended recipient, an employee or agent of
the intended recipient who is responsible for delivering it to the intended recipient, or if you
believe that you have received this communication in error, please notify the sender immediately by
return e-mail and promptly delete this e-mail, including attachments without reading or saving them
in any manner. The unauthorized use, dissemination, distribution, or reproduction of this e-mail,
including attachments, is prohibited and may be unlawful. If you have received this email in error,
please notify us immediately by e-mail or telephone and delete the e-mail and the attachments (if
any).