代码之家  ›  专栏  ›  技术社区  ›  Ian Baget

有与PHP函数htmlspecialchars()等价的Python吗?

  •  13
  • Ian Baget  · 技术社区  · 17 年前

    7 回复  |  直到 14 年前
        1
  •  12
  •   Karl Guertin    17 年前

    我知道的最接近的事情是 cgi.escape

        2
  •  6
  •   Agonych    16 年前
    from django.utils.html import escape
    print escape('<div class="q">Q & A</div>')
    
        3
  •  3
  •   Nicolas Dumazet    17 年前

    你可能想 xml.sax.saxutils.escape

    from xml.sax.saxutils import escape
    escape(unsafe, {'"':'&quot;'}) # ENT_COMPAT
    escape(unsafe, {'"':'&quot;', '\'':'&#039;'}) # ENT_QUOTES
    escape(unsafe) # ENT_NOQUOTES
    

    看看 xml.sax.saxutils.quoteattr ,可能对你更有用

        4
  •  1
  •   sykora    17 年前

    html.entities htmlentitydefs 包含一个字典 codepoint2name 它能满足你的需要。

    >>> import html.entities
    >>> html.entities.codepoint2name[ord("&")]
    'amp'
    >>> html.entities.codepoint2name[ord('"')]
    'quot'
    
        5
  •  1
  •   garlon4    15 年前

    text.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")
    

    PHP只使用htmlspecialchar来转义这四个实体。请注意,如果在PHP中设置了entu引号,则需要将引号替换为&039;而不是"。

        6
  •  1
  •   AlejandroVD    10 年前

    在@garlon4答案的基础上,您可以定义自己的答案 htmlspecialchars(s)

    def htmlspecialchars(text):
        return (
            text.replace("&", "&amp;").
            replace('"', "&quot;").
            replace("<", "&lt;").
            replace(">", "&gt;")
        )
    
        7
  •  0
  •   Paul Tarjan    17 年前

    如果您使用的是django1.0,那么您的模板变量已经被编码并准备好显示。您还可以使用 safe 操作人员 {{ var|safe }} 如果你不想在全局范围内打开它。

    推荐文章