簡體   English   中英

如何將字符串轉換為帶有HTML實體的字符串?

[英]How convert a String to a String with HTML entities?

我正在尋找一種方法,最好是在python ,但PHP也是可以的,甚至是在線站點,也可以將字符串轉換為

"Wählen"

變成像

"Wählen"

也就是說,將每個ISO 8859-1字符/符號替換為其HTML實體。

echo htmlentities('Wählen', 0, 'utf-8');

^ PHP

PS根據需要在哪里顯示編碼的字符串來學習參數

// does not encode quotes
echo htmlentities('"Wählen"', 0, 'utf-8');
// encodes quotes
echo htmlentities('"Wählen"', ENT_QUOTES, 'utf-8');

像這樣

 $html="Wählen";
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'ISO-8859-1');
// OR  $html = htmlentities($html, ENT_COMPAT, 'ISO-8859-1');
echo $new = htmlspecialchars($html, ENT_QUOTES);

對於Python3

>>> import html.entities
>>> reventities = {k:'&'+v+';' for v,k in html.entities.entitydefs.items()}
>>> "".join(reventities.get(i, i) for i in "Wählen")
'Wählen'

另一種(可能更快)的方式

>>> toentity = {k: '&'+v+';' for k,v in html.entities.codepoint2name.items()}
>>> "Wählen".translate(toentity)
'Wählen'

蟒蛇:

# -*- coding: utf-8 -*-
from htmlentitydefs import codepoint2name

def uni_to_html(s):
    new_s = ""
    for c in s:
        try:
            new_s += '&{};'.format(codepoint2name[ord(c)])
        except KeyError:
            new_s += c
    return new_s

print uni_to_html(u"Wählen")  # Wählen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM