Home  >  Article  >  Backend Development  >  PHP converts a string into a class of HTML entity reference

PHP converts a string into a class of HTML entity reference

WBOY
WBOYOriginal
2016-07-25 09:05:32926browse
  1. class HtmlEncode {

  2. static $_convertToHtmlEntitiesSrcEncoding='UTF-8';
  3. /**
  4. * Convert non-ASCII strings into HTML entities
  5. *
  6. * @example HtmlEncode::encode("I believe it"); //Output: I believe it
  7. * @param string $s The string to be encoded
  8. * @return string Returns HTML entity reference
  9. */
  10. public static function encode($s,$srcEncoding='UTF-8') {
  11. self::$_convertToHtmlEntitiesSrcEncoding=$srcEncoding;
  12. return preg_replace_callback('|[^x00-x7F]+|',array(__CLASS__,'_convertToHtmlEntities'),$s);
  13. }
  14. public static function _convertToHtmlEntities($data) {
  15. if (is_array($data)) {
  16. $chars=str_split(iconv(self::$_convertToHtmlEntitiesSrcEncoding,"UCS-2BE",$data[0]),2);
  17. $chars=array_map(array(__CLASS__,__FUNCTION__),$chars);
  18. return join("",$chars);
  19. } else {
  20. $code=hexdec(sprintf("%02s%02s;",dechex(ord($data {0})),dechex(ord($data 吓死猫的老鼠))));
  21. return sprintf("%s;",$code);
  22. }
  23. }
  24. }

复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn