把html标签转换为实体
/*
可以处理数组中的代码,他们的作用是可以把一个数组或字符串中的字符转化为html实体,可以防止页面的跨站问题,
那么我们看到他的转换就是将'&','"','<','>'转化为'&amp;', '&quot;', '&lt;', '&gt;'。
但是这里面会有一些问题,如'& #x5FD7;'这样的16进制的html字符,为了防止这样的字符被错误转译,所以又使用了正则进行匹配,
把这样的字符又转换回来。
*/

 1 function dhtmlspecialchars($string, $flags = null) {
 2     if(is_array($string)) {
 3         foreach($string as $key => $val) {
 4             $string[$key] = dhtmlspecialchars($val, $flags);
 5         }
 6     } else {
 7         if($flags === null) {
 8             $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
 9             if(strpos($string, '&amp;#') !== false) {
10                 //过滤掉类似&#x5FD7的16进制的html字符
11                 $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
12             }
13         } else {
14             if(PHP_VERSION < '5.4.0') {
15                 $string = htmlspecialchars($string, $flags);
16             } else {
17                 if(strtolower(CHARSET) == 'utf-8') {
18                     $charset = 'UTF-8';
19                 } else {
20                     $charset = 'ISO-8859-1';
21                 }
22                 $string = htmlspecialchars($string, $flags, $charset);
23             }
24         }
25     }
26     return $string;
27 }

 

posted on 2013-06-20 15:01  睡着的糖葫芦  阅读(5118)  评论(0编辑  收藏  举报