php - 如何使用 PHP 将所有字符转换为等效的 html 实体

标签 php string utf-8 encode html-entities

我想把这个 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/

相关文章:

c - 纯C代码示例中的utf8到char编码

php - 页面刷新时数据库被填充

php - PHP和MySQL-mysqli_free_result()期望参数1为mysqli_result,在第110行给出的 bool 值

php - 如何使用ajax显示div中的所有复选框值

javax.validation : Constraint to validate a string length in bytes

mysql - utf8_general_ci和utf8_unicode_ci有什么区别?

mysql - 如何选择第一个字符的唯一列表[MySQL]

javascript - 编程 php 并在 html 表单上提醒 javascript

c++ - std::string 复制构造函数段错误

ruby - 类型错误 : wrong argument type String (expected Module) when trying to use rspec