现在的位置: 首页 > web前端 > 正文

PHP中htmlentities跟htmlspecialchars的区别

2019年10月30日 web前端 ⁄ 共 1189字 ⁄ 字号 评论关闭

htmlentities跟htmlspecialchars都是用于将字符串的特殊字符中转成HTML字符实体。只是htmlspecialcharsl转义的特殊字符集只有5个,

'&' (ampersand)     => '&' 
'"' (double quote)    => '"'     when ENT_NOQUOTES is not set. 
''' (single quote)      => '''    only when ENT_QUOTES is set. 
'<' (less than)          => '&lt;' 
'>' (greater than)     => '&gt;'

而htmlentities转义的特殊字符集是完整的HTML字符实体集。

对于这两个函数,php手册上都是英文做的解释,其中在htmlentities函数的说明部分有这么一段英文:

This function is identical(完全相同的) to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents(HTML
character entity equivalents译为
HTML字符实体等价物) are translated into these entities.

从这句话中我们也可以看出来这两个函数虽然基本功能差不多,但是还是有细微的差别在里面的。再仔细看htmlspecialchars函数里面的一段话:

Certain characters(其实就是'&', 双引号(没有设置ENT_NOQUOTES时才会转义), 单引号(当且仅当设置ENT_QUOTES才会转义), '<', '>') have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function
returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead. 

注:使用这两个函数时最后指明编码格式哦。

参考链接

  1. W3Schools.com - Symbols Entities
  2. 这是一个完整的字符实体参考 Webstandards.org - Symbol Entities
  3. http://www.neoease.com/using-html-symbol-entities/

抱歉!评论已关闭.