当前位置: 移动技术网 > IT编程>开发语言>PHP > php实现HTML实体编号与非ASCII字符串相互转换类实例

php实现HTML实体编号与非ASCII字符串相互转换类实例

2017年12月12日  | 移动技术网IT编程  | 我要评论

郭湘成,cz6600航班,ailete408

html实体符号被用作实现保留字符(reserved characters)或者表达键盘无法输入的一些常用字符。在大多数浏览器中默认的字符集为iso-8859-1。html实体符号我们在网页设计中经常用到。

例如:


因工作需要,编写了一个html实体编号与非ascii字符串相互转换类,代码如下:

htmlentitie.class.php

<?php
/**
 * html实体编号与非ascii字符串相互转换类
 * date: 2016-09-07
 * author: fdipzone
 * ver: 1.0
 *
 * func:
 * public encode 字符串转为html实体编号
 * public decode html实体编号转为字符串
 * private _converttohtmlentities 转换为html实体编号处理
 */
class htmlentitie{ // class start

 public static $_encoding = 'utf-8';

 /**
  * 字符串转为html实体编号
  * @param string $str  字符串
  * @param string $encoding 编码
  * @return string
  */
 public static function encode($str, $encoding='utf-8'){
  self::$_encoding = $encoding;
  return preg_replace_callback('|[^\x00-\x7f]+|', array(__class__, '_converttohtmlentities'), $str);
 }

 /**
  * html实体编号转为字符串
  * @param string $str  html实体编号字符串
  * @param string $encoding 编码
  * @return string
  */
 public static function decode($str, $encoding='utf-8'){
  return html_entity_decode($str, null, $encoding);
 }

 /**
  * 转换为html实体编号处理
  * @param mixed $data 待处理的数据
  * @param string
  */
 private static function _converttohtmlentities($data){
  if(is_array($data)){
   $chars = str_split(iconv(self::$_encoding, 'ucs-2be', $data[0]), 2);
   $chars = array_map(array(__class__, __function__), $chars);
   return implode("", $chars);
  }else{
   $code = hexdec(sprintf("%02s%02s;", dechex(ord($data {0})), dechex(ord($data {1})) ));
   return sprintf("&#%s;", $code);
  }
 }

} // class end
?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网