htmlspecialchars()和htmlentities()之间的区别是什么?什么时候我应该用一种或另一种?
当前回答
htmlentities -将所有适用的字符转换为HTML实体。
htmlspecialchars -将特殊字符转换为HTML实体。
翻译执行以下翻译字符:
'&'(&)变成'&' “”(双引号)在没有设置ENT_NOQUOTES时变为“"”。 只有当设置了ENT_QUOTES时,"'"(单引号)才变为'''(或')。 <(小于)变成了< '>'(大于)变成'>'
你可以检查下面的代码,以了解什么是htmlentities和htmlspecialchars:
https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b
其他回答
PHP htmlentities文档:
这个函数在所有方面都与htmlspecialchars()相同,除了htmlentities(),所有具有HTML字符实体等价的字符都被翻译成这些实体。
从PHP文档htmlspecialchars:
某些字符在HTML中有特殊的意义,如果要保留它们的含义,就应该用HTML实体来表示。这个函数返回一个包含这些转换的字符串;所做的翻译是那些对日常web编程最有用的。如果需要翻译所有HTML字符实体,请使用htmlentities()。
区别在于编码的内容。选项是所有(实体)或“特殊”字符,如&号、双引号和单引号、小于和大于(specialchars)。
只要可能,我更喜欢使用htmlspecialchars。
例如:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
因为:
有时在编写XML数据时,不能在XML文件中使用HTML实体。 因为htmlentities替换的字符比htmlspecialchars多。这是不必要的,这会降低PHP脚本的效率,从而降低HTML代码的可读性。
htmlentities只在页面使用ASCII或LATIN-1等编码而不是UTF-8,并且处理数据的编码与页面的编码不同时才有必要。
htmlspecialchars()和htmlentities()之间的区别非常小。让我们来看一些例子:
htmlspecialchars
htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into < b >. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.
echo htmlspecialchars('An example <br>'); // This will print - An example < br >
echo htmlspecialchars('µ †'); // This will print - µ †
htmlentities
Htmlentities (string $string)非常类似于htmlspecialchars,需要多个参数,其中第一个参数是字符串,所有其他参数都是可选的(某些标志,某些编码等)。与htmlspecialchars不同,htmlentities不仅将字符串中的特殊字符转换为HTML实体,还将所有适用的字符转换为HTML实体。
echo htmlentities('An example <br>'); // This will print - An example < br >
echo htmlentities('µ †'); // This will print - µ †
当你只想让你的字符串是XML和HTML安全的时候,你应该使用htmlspecialchars($strText, ENT_QUOTES):
例如,encode
& to & “To”; < to < >到> '到'
但是,如果文本中还有Unicode或不常见符号的额外字符,则应该使用htmlentities()来确保它们在HTML页面中正确显示。
注:
'只会被htmlspecialchars()编码到'如果传入ENT_QUOTES选项。& # 039;是更安全的使用然后'由于旧版本的Internet Explorer不支持'实体。 从技术上讲,>不需要按照XML规范进行编码,但是为了与<被编码的要求保持一致,通常也会对它进行编码。
htmlspecialchars()进行最少的编码,以确保字符串不会被解析为HTML。这使得您的字符串比使用htmlentities()对所有具有编码的内容进行编码时更易于阅读。
推荐文章
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在php中创建可选参数?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 如何从一个查询插入多行使用雄辩/流利
- 在PHP单元测试执行期间,如何在CLI中输出?