本文介紹了如何使用 PHP 將所有字符轉換為等效的 html 實體的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想把這個 hello@domain.com
轉換成
I want to convert this hello@domain.com
to
hello@domain.com
我試過了:
url_encode($string)
這提供了我輸入的相同字符串,返回時將@ 符號轉換為 %40
this provides the same string I entered, returned with the @ symbol converted to %40
也嘗試過:
htmlentities($string)
這提供了相同的字符串.
this provides the same string right back.
我使用的是 UTF8 字符集.不知道這是否有所作為....
I am using a UTF8 charset. not sure if this makes a difference....
推薦答案
就這樣(假設是 UTF-8,但更改起來很簡單):
Here it goes (assumes UTF-8, but it's trivial to change):
function encode($str) {
$str = mb_convert_encoding($str , 'UTF-32', 'UTF-8'); //big endian
$split = str_split($str, 4);
$res = "";
foreach ($split as $c) {
$cur = 0;
for ($i = 0; $i < 4; $i++) {
$cur |= ord($c[$i]) << (8*(3 - $i));
}
$res .= "&#" . $cur . ";";
}
return $res;
}
編輯推薦使用unpack
的替代方法::>
function encode2($str) {
$str = mb_convert_encoding($str , 'UTF-32', 'UTF-8');
$t = unpack("N*", $str);
$t = array_map(function($n) { return "&#$n;"; }, $t);
return implode("", $t);
}
這篇關于如何使用 PHP 將所有字符轉換為等效的 html 實體的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!