php实现HTML实体编号与非ASCII字符串相互转换类实例
作者:傲雪星枫 时间:2023-11-15 06:12:14
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
?>
标签:php,ascii,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
django admin 后台实现三级联动的示例代码
2023-11-04 04:01:43
Django之使用内置函数和celery发邮件的方法示例
2022-03-04 17:15:26
![](https://img.aspxhome.com/file/2023/2/120592_0s.png)
Python爬取qq空间说说的实例代码
2021-04-28 01:29:50
彻底删除thinkphp3.1案例blog标签的方法
2023-11-21 12:01:01
javascript中mouseenter与mouseover的异同
2024-05-02 16:11:54
![](https://img.aspxhome.com/file/2023/2/132872_0s.png)
JS+ASP实现无刷新新闻列表方法
2007-08-22 12:44:00
django中F与Q查询的使用
2022-11-20 19:23:22
![](https://img.aspxhome.com/file/2023/3/93483_0s.png)
SQL查询效率-100w数据查询只要1秒
2008-08-20 18:25:00
Javascript中的基本类型和引用类型概述说明
2024-04-18 09:37:04
![](https://img.aspxhome.com/file/2023/0/136370_0s.png)
Python装饰器原理与基本用法分析
2023-04-29 10:46:32
VS 2008的性能改进
2007-10-07 21:42:00
Python 正则表达式入门(初级篇)
2021-12-03 23:41:12
python实现循环语句1到100累和
2023-05-15 15:39:38
python可视化爬虫界面之天气查询
2022-09-24 07:34:54
![](https://img.aspxhome.com/file/2023/6/95216_0s.png)
asp中的rs.open于conn.execute的区别
2009-10-29 12:12:00
SQL截取字符串函数分享
2011-11-03 17:07:37
js生成随机数(指定范围)的实例代码
2024-04-17 10:29:42
Python数据库小程序源代码
2024-01-17 06:28:30
在Django中限制已登录用户的访问的方法
2023-02-20 19:55:14
基于Python实现二维图像双线性插值
2023-08-13 07:46:45
![](https://img.aspxhome.com/file/2023/4/61984_0s.png)