htmlspecialchars()和htmlentities()之间的区别是什么?什么时候我应该用一种或另一种?


当前回答

当你只想让你的字符串是XML和HTML安全的时候,你应该使用htmlspecialchars($strText, ENT_QUOTES):

例如,encode

& to & “To”; < to &lt; >到&gt; '到&#039;

但是,如果文本中还有Unicode或不常见符号的额外字符,则应该使用htmlentities()来确保它们在HTML页面中正确显示。

注:

'只会被htmlspecialchars()编码到&#039;如果传入ENT_QUOTES选项。& # 039;是更安全的使用然后&apos;由于旧版本的Internet Explorer不支持&apos;实体。 从技术上讲,>不需要按照XML规范进行编码,但是为了与<被编码的要求保持一致,通常也会对它进行编码。

其他回答

一个小例子,我需要在一个函数中索引2个客户端名称:

[1] => Altisoxxce Soluxxons S.à r.l.
[5] => Joxxson & Joxxson

我原来$term = get_term_by('name', htmlentities($name), '客户端');这导致术语名只包括&号数组项(&),而不包括重音项。但是当我将变量设置改为htmlspecialchars时,两者都能够通过函数运行。希望这能有所帮助!

这是用htmlentities编码的。

implode("\t", array_values(get_html_translation_table(HTML_ENTITIES))):

" & < > ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ œ Š š Ÿ ƒ ˆ ˜ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ υ φ χ ψ ω ϑ ϒ ϖ       ‌ ‍ ‎ ‏ – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ′ ″ ‹ › ‾ ⁄ € ℑ ℘ ℜ ™ ℵ ← ↑ → ↓ ↔ ↵ ⇐ ⇑ ⇒ ⇓ ⇔ ∀ ∂ ∃ ∅ ∇ ∈ ∉ ∋ ∏ ∑ − ∗ √ ∝ ∞ ∠ ∧ ∨ ∩ ∪ ∫ ∴ ∼ ≅ ≈ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊄ ⊆ ⊇ ⊕ ⊗ ⊥ ⋅ ⌈ ⌉ ⌊ ⌋ ⟨ ⟩ ◊ ♠ ♣ ♥ ♦

这是用htmlspecialchars编码的。

implode("\t", array_values(get_html_translation_table(HTML_SPECIALCHARS))):

& < >

我刚刚发现了get_html_translation_table函数。你传递给它HTML_ENTITIES或者HTML_SPECIALCHARS,它会返回一个数组,里面是要被编码的字符以及它们的编码方式。

Htmlspecialchars可以被使用:

When there is no need to encode all characters which have their HTML equivalents. If you know that the page encoding match the text special symbols, why would you use htmlentities? htmlspecialchars is much straightforward, and produce less code to send to the client. For example: echo htmlentities('<Il était une fois un être>.'); // Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;. // ^^^^^^^^ ^^^^^^^ echo htmlspecialchars('<Il était une fois un être>.'); // Output: &lt;Il était une fois un être&gt;. // ^ ^ The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set. When the data will be processed not only through a browser (to avoid decoding HTML entities), If the output is XML (see the answer by Artefacto).

htmlentities -将所有适用的字符转换为HTML实体。

htmlspecialchars -将特殊字符转换为HTML实体。

翻译执行以下翻译字符:

'&'(&)变成'&' “”(双引号)在没有设置ENT_NOQUOTES时变为“"”。 只有当设置了ENT_QUOTES时,"'"(单引号)才变为'&#039;'(或')。 <(小于)变成了&lt; '>'(大于)变成'&gt;'

你可以检查下面的代码,以了解什么是htmlentities和htmlspecialchars:

https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b