一般來講,PHP要在HTML輸出 ' " & < > 等特殊符號,必須轉成 &nbsp; &#32; 之類的編碼才能顯示。

PHP 提供轉換函式:
htmlentities()            -> 字元轉編碼
html_entity_decode()      -> 編碼轉字元

因為 htmlentities() 是無差別地圖兵器,如果只是要轉幾個特殊符號,使用 htmlspecialchars() 就可以了。

節錄 tw.php.net 對 htmlspecialchars 的敘述:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

如果使用 htmlentities(),要轉換的字串裡有中文字的話,記得要加 ENT_QUOTES 參數讓 htmlentities() 忽略雙字元:

<?php
$str = "中文字測試&<>'";
echo htmlentities($str,ENT_QUOTES,"UTF-8");
?>

 

arrow
arrow
    全站熱搜

    bigair 發表在 痞客邦 留言(0) 人氣()