免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2482 | 回复: 1
打印 上一主题 下一主题

PHP将字符串转为HTML实体引用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-08-02 20:46 |只看该作者 |倒序浏览
PHP将字符串转为HTML实体引用




没事发个PHP将字符串转为HTML实体引用。

上代码


Php代码
  1. 1.  
  2. 2.class HtmlEncode {   
  3. 3.    static $_convertToHtmlEntitiesSrcEncoding='UTF-8';   
  4. 4.  
  5. 5.    /**  
  6. 6.     * 将非ASCII字符串转换成HTML实体  
  7. 7.     *  
  8. 8.     * @example HtmlEncode::encode("我信了"); //输出:我信了  
  9. 9.     * @param string $s 要进行编码的字符串  
  10. 10.     * @return string 返回HTML实体引用  
  11. 11.     */  
  12. 12.    public static function encode($s,$srcEncoding='UTF-8') {   
  13. 13.        self::$_convertToHtmlEntitiesSrcEncoding=$srcEncoding;   
  14. 14.        return preg_replace_callback('|[^\x00-\x7F]+|',array(__CLASS__,'_convertToHtmlEntities'),$s);   
  15. 15.    }   
  16. 16.  
  17. 17.    public static function _convertToHtmlEntities($data) {   
  18. 18.        if (is_array($data)) {   
  19. 19.            $chars=str_split(iconv(self::$_convertToHtmlEntitiesSrcEncoding,"UCS-2BE",$data[0]),2);   
  20. 20.            $chars=array_map(array(__CLASS__,__FUNCTION__),$chars);   
  21. 21.            return join("",$chars);   
  22. 22.        } else {   
  23. 23.            $code=hexdec(sprintf("%02s%02s;",dechex(ord($data {0})),dechex(ord($data {1}))));   
  24. 24.            return sprintf("&#%s;",$code);   
  25. 25.        }   
  26. 26.    }   
  27. 27.  
  28. 28.}  
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-08-04 09:57 |只看该作者
htmlentities

(PHP 4, PHP 5)

htmlentities — Convert all applicable characters to HTML entities
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP