php - Twig 中 escape ('html' ) 和 escape ('html_attr' ) 的区别

标签 php escaping twig

自版本 1.9.0 起,Twigescape 过滤器提供 html_attr 策略(参见 documentation )。

html 策略使用 htmlspecialchars PHP 函数(通过快速查看源代码可以确认这一点)。 html_attr 策略使用了一系列自定义替换,这些替换似乎最终具有相同的效果。

这两种策略有区别吗?

最佳答案

source说:

/*
 * While HTML supports far more named entities, the lowest common denominator
 * has become HTML5's XML Serialisation which is restricted to the those named
 * entities that XML supports. Using HTML entities would result in this error:
 *     XML Parsing Error: undefined entity
 */

在实践中,html 策略只会更改在 HTML 中具有特殊含义的字符,而 html_attr 策略会替换几乎所有非字母数字字符,包括空格。看例子:

看到这个文本,好吗?

raw:       See this <b>text</b>, OK?
html:      See this &lt;b&gt;text&lt;/b&gt;, OK?
html_attr: See&#x20;this&#x20;&lt;b&gt;text&lt;&#x2F;b&gt;,&#x20;OK&#x3F;

据我了解,对于HTML,你可以使用html策略,对于XML文档,你最好使用html_attr策略,但我没有在实践中尝试过.

关于php - Twig 中 escape ('html' ) 和 escape ('html_attr' ) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038048/

相关文章:

php - Twig 赋值运算符

php - 如何在twig中转换数组 block

php - 如何使 mysql 搜索允许两个单独的搜索类别?

php - foreach 不会在中断时停止循环

PHP 断行 ".\n"在电子邮件正文中不起作用。线条正在消失

regex - 如何在正则表达式字符类中转义右方括号?

java - 正则表达式非法转义字符

php - mysqli_real_escape_string 使用什么类型的引号?

javascript - JSON.stringify 不转义?

symfony - Twig Symfony2获取请求变量