php中将字符串转为HTML的实体引用的一个类
程序员文章站
2022-05-17 10:06:07
复制代码 代码如下:class htmlencode { static $_conve...
复制代码 代码如下:
class htmlencode {
static $_converttohtmlentitiessrcencoding='utf-8';
/**
* 将非ascii字符串转换成html实体
*
* @example htmlencode::encode("我信了"); //输出:我信了
* @param string $s 要进行编码的字符串
* @return string 返回html实体引用
*/
public static function encode($s,$srcencoding='utf-8') {
self::$_converttohtmlentitiessrcencoding=$srcencoding;
return preg_replace_callback('|[^\x00-\x7f]+|',array(__class__,'_converttohtmlentities'),$s);
}
public static function _converttohtmlentities($data) {
if (is_array($data)) {
$chars=str_split(iconv(self::$_converttohtmlentitiessrcencoding,"ucs-2be",$data[0]),2);
$chars=array_map(array(__class__,__function__),$chars);
return join("",$chars);
} else {
$code=hexdec(sprintf("%02s%02s;",dechex(ord($data {0})),dechex(ord($data {1}))));
return sprintf("%s;",$code);
}
}
}