我想把这个 hello@domain.com
转换成
hello@domain.com
我试过:
url_encode($string)
这提供了我输入的相同字符串,返回时带有转换为 %40
的 @ 符号
也尝试过:
htmlentities($string)
这提供了相同的字符串。
我使用的是 UTF8 字符集。不确定这是否有所作为....
最佳答案
这里是(假定为 UTF-8,但更改起来很简单):
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 - 如何使用 PHP 将所有字符转换为等效的 html 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3005116/