note 61204 deleted from function.htmlentities by nlopess

From: Date: Sat, 28 Jan 2006 10:55:12 +0000
Subject: note 61204 deleted from function.htmlentities by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-102605@lists.php.net to get a copy of this message
Note Submitter: timburgan <at> gmail <dot> com ---- To encode characters within a string to their HTML character code (in the format &#xx;), use the following function encode_entities(). A list of HTML character codes can be found at: http://www.ascii.cl/htmlcodes.htm Note: To dencode a string that contains HTML character codes (in the format &#xx;), use the function unicode_decode(), listed in the comments of http://php.net/manual/function.html-entity-decode.php <?php /** * Encode each char in a string to its HTML code. * Characters encoded by this function can be decoded * by unicode_decode(). * * This function will work with PHP >= 3.0.9, 4, 5. * * @author Tim Burgan <timburgan@gmail.com> * @version 1.0.0 * @link http://timburgan.com/ * @link http://php.net/manual/function.htmlentities.php * @see http://php.net/manual/function.html-entity-decode.php * @param string $string String to encode * @param bool $encodeAll Optional. Default is false. If true all chars are encoded, if false, only non-alpha-numeric and space chars are encoded. * @return string Returns a string of encoded chars */ function unicode_entities($string, $encodeAll = false) { // declare variables $chars = array(); $ent = null; // split string into array $chars = preg_split("//", $string, -1, PREG_SPLIT_NO_EMPTY);; // encode each character for ( $i = 0; $i < count($chars); $i++ ) { if ( preg_match("/^(\w| )$/",$chars[$i]) && $encodeAll == false ) $ent[$i] = $chars[$i]; else $ent[$i] = "&#" . ord($chars[$i]) . ";"; } if ( sizeof($ent) < 1) return ''; return implode($ent); } ?> Usage: <?php $string = '<a href="http://timburgan.com" rel="external" title="Go to timburgan.com">Tim Burgan</a>'; echo unicode_entities($string); ?> Output: &#60;a href&#61;&#34;http&#58;&#47;&#47;timburgan&#46;com&#34; rel&#61;&#34;external&#34; title&#61;&#34;Go to timburgan&#46;com&#34;&#62;Tim Burgan&#60;&#47;a&#62;

« previous php.notes (#102605) next »