簡體   English   中英

用PHP將特殊字符轉換為相應的HTML代碼的最佳方法是什么?

[英]What is the best way to convert special characters to the corresponding HTML Codes with PHP?

我想轉換所有內容,例如空格,單/雙引號,換行符等。

這是一個示例輸入(感謝som_nangia ):

Escape Check < &quot;escape these&quot; > <“and these”> <html><tr><td></td></tr></html> 'these will need escaping too' ‘ so will these’ <script>&nbsp;</script>

以下是我正在考慮的選項:

<pre>Escape Check < &quot;escape these&quot; > <“and these”> <html><tr><td></td></tr></html> 'these will need escaping too' ' so will these' <script>&nbsp;</script></pre>

/**
 * Encoding html special characters, including nl2br
 * @param string  $original
 * @return string
 */
function encode_html_sp_chars($original) {
    $table = get_html_translation_table(HTML_ENTITIES);
    $table[' '] = '&nbsp;';
    $encoded = strtr($original, $table);
    return nl2br($encoded);
}

我已經嘗試了htmlspecialcharshtmlentities ,但是它們都不對空格進行編碼。

使用htmlspecialchars

echo htmlspecialchars($string);

對於您的情況,請以這種方式傳遞兩個參數:

echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

感謝zerkmsPhil

說明

某些字符在HTML中具有特殊意義,如果要保留其含義,則應由HTML實體表示。 該函數返回經過這些轉換的字符串。 如果您需要翻譯具有關聯的命名實體的所有輸入子字符串,請改用htmlentities()。

如果傳遞給此函數的輸入字符串和最終文檔共享相同的字符集,則此函數足以准備將輸入包含在HTML文檔的大多數上下文中。 但是,如果輸入可以表示未在最終文檔字符集中編碼的字符,而您希望保留這些字符(作為數字或命名實體),則此函數和htmlentities()(僅對具有命名實體的子字符串進行編碼)等值)可能不足。 您可能不得不使用mb_encode_numericentity()。

最好的方法可能是

例:

function encode_html_sp_chars($original) {
    $encoded = htmlentities($original, ENT_QUOTES, "UTF-8");
    $encoded = str_replace(' ', '&nbsp;', $encoded);
    return nl2br($encoded);
}

暫無
暫無

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

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