将所有符号转换为 html 个实体

Convert ALL symbols to html entities

在 PHP 中,使用内置函数似乎不包含特殊符号和新符号。 ALL 包括 3 个月前发布的那些。想用混合符号转换字符串,例如:

δϱж ☎

进入

𝕃𝕆𝕃 𝔯𝔬𝔠𝔰 𝓂𝓎 δϱж ☎

(浏览器将呈现相同的内容)

我看到这是即时完成的。我们在这里谈论无数的符号。谁知道将来还会有多少。

他们是如何实现这一目标的?他们不可能真的拥有每个符号及其实体的 1000 多个键数组?

我已经回答了所有相关问题,到目前为止还没有成功。

简单:编码不使用任何特殊知识。输入是一个数字字符值,输出是&#<decimal-value>;

How are they achieving this? No way they really have a 1000+ key array of every single symbol and its entity?

他们 do 事实上有一个 translation table 并且它确实包含你在问题中的所有符号(和table 有超过 1500 个条目 :)).

Fiddle

此函数会将 [0-9A-Za-z ] 以外的每个字符(当前和未来)转换为数字实体。假定 UTF-8 字符编码:

function html_entity_encode_all($s) {
    $out = '';
    for ($i = 0; isset($s[$i]); $i++) {
        // read UTF-8 bytes and decode to a Unicode codepoint value:
        $x = ord($s[$i]);
        if ($x < 0x80) {
            // single byte codepoints
            $codepoint = $x;
        } else {
            // multibyte codepoints
            if ($x >= 0xC2 && $x <= 0xDF) {
                $codepoint = $x & 0x1F;
                $length = 2;
            } else if ($x >= 0xE0 && $x <= 0xEF) {
                $codepoint = $x & 0x0F;
                $length = 3;
            } else if ($x >= 0xF0 && $x <= 0xF4) {
                $codepoint = $x & 0x07;
                $length = 4;
            } else {
                // invalid byte
                $codepoint = 0xFFFD;
                $length = 1;
            }
            // read continuation bytes of multibyte sequences:
            for ($j = 1; $j < $length; $j++, $i++) {
                if (!isset($s[$i + 1])) {
                    // invalid: string truncated in middle of multibyte sequence
                    $codepoint = 0xFFFD;
                    break;
                }
                $x = ord($s[$i + 1]);
                if (($x & 0xC0) != 0x80) {
                    // invalid: not a continuation byte
                    $codepoint = 0xFFFD;
                    break;
                }
                $codepoint = ($codepoint << 6) | ($x & 0x3F);
            }
            if (($codepoint > 0x10FFFF) ||
                ($length == 2 && $codepoint < 0x80) ||
                ($length == 3 && $codepoint < 0x800) ||
                ($length == 4 && $codepoint < 0x10000)) {
                // invalid: overlong encoding or out of range
                $codepoint = 0xFFFD;
            }
        }

        // have codepoint, now output:
        if (($codepoint >= 48 && $codepoint <= 57) ||
            ($codepoint >= 65 && $codepoint <= 90) ||
            ($codepoint >= 97 && $codepoint <= 122) ||
            ($codepoint == 32)) {
            // leave plain 0-9, A-Z, a-z, and space unencoded
            $out .= $s[$i];
        } else {
            // all others as numeric entities
            $out .= '&#' . $codepoint . ';';
        }
    }
    return $out;
}

对于解码,可以使用标准函数html_entity_decode