当前位置:首页 > PHP教程 > PHP高级教程

php中将字符串转为HTML的实体引用的一个类

复制代码 代码如下:

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);
            }
        }     
    }


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!