String encoding for HTML

I find this a handy function to encompass a number of different string encoding routines. It allows you to do entity encoding (ÿ), hex (á), html (&aecute;), or url encoding (%E1).

It uses a number of defined constants for convenience.

PHP:
  1. /**
  2. * Encode a string for HTML usage
  3. *
  4. * This method will encode characters (such as accented characters, &,
  5. *>, and so on) to either their equivelant entities in decimal (ÿ),
  6. * hex (á) or html (&aecute;).  It can also be used to convert to
  7. * url encode, %E1.
  8. *
  9. * Encoding will only happen to characters greater than '~' (chr(127)).
  10. *
  11. * If an incorrect encoding type is passed it will simply return the
  12. * string in the same state.
  13. *
  14. * @param string $str The string to encode
  15. * @param integer $type The type of encoding to use
  16. * @return string
  17. * @access public
  18. */
  19.  
  20. define('ENC_TO_DEC', 0);
  21. define('ENC_TO_HEX', 1);
  22. define('ENC_TO_ENT', 2);
  23. define('ENC_TO_URL', 3);
  24.  
  25. function encode_html($str, $type = ENC_TO_DEC)
  26. {
  27.     $result = '';
  28.     switch($type) {
  29.        case ENC_TO_ENT:
  30.            $fixed = htmlentities($str, ENT_QUOTES);
  31.            $trans = array();
  32.            for ($i = 127; $i <255; $i++) {
  33.                $trans[chr($i)] = "&#{$i};";
  34.            }
  35.            $result = strtr($fixed, $trans);
  36.            break;
  37.        case ENC_TO_DEC:
  38.            for ($i = 0; $i <strlen($str); $i++) {
  39.                $cdec = ord($str{$i});
  40.                $result .= ($cdec <= 127) ? $str{$i} : "&#{$cdec};";
  41.            }
  42.            break;
  43.        case ENC_TO_HEX:
  44.            for ($i = 0; $i <strlen($str); $i++) {
  45.                $cdec = ord($str{$i});
  46.                $result .= ($cdec <= 127) ? $str{$i} : '&#x' . strtoupper(dechex($cdec)) . ';';
  47.            }
  48.            break;
  49.        case ENC_TO_URL:
  50.            $result = urlencode($str);
  51.            break;
  52.        default:
  53.            $result = $str;
  54.            break;
  55.     }
  56.     return $result;
  57. }

0 Responses to “String encoding for HTML”


  1. No Comments

Leave a Reply

You must login to post a comment.




Mp3 sparks Allofmp3