How to convert all characters to their html entity

2019-01-08 17:22发布

I want to convert this hello@domain.com to

hello@domain.com

I have tried:

url_encode($string)

this provides the same string I entered, returned with the @ symbol converted to %40

also tried:

htmlentities($string)

this provides the same string right back.

I am using a UTF8 charset. not sure if this makes a difference....

3条回答
手持菜刀,她持情操
2楼-- · 2019-01-08 18:01
function uniord($char) {

     $k=mb_convert_encoding($char , 'UTF-32', 'UTF-8');

     $k1=ord(substr($k,0,1));

     $k2=ord(substr($k,1,1));

     $value=(string)($k2*256+$k1);

     return $value;

}

the above function works for 1 character but if you have a string you can do like this

$string="anytext";

$arr=preg_split(//u,$string,-1,PREG_SPLIT_NO_EMPTY);

$temp=" ";

foreach($arr as $v){

    $temp="&#".uniord($v);//prints the equivalent html entity of string

}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-08 18:11

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;
}

EDIT Recommended alternative using 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);
}
查看更多
地球回转人心会变
4楼-- · 2019-01-08 18:14

Much easier way to do this:

function convertToNumericEntities($string) {
    $convmap = array(0x80, 0x10ffff, 0, 0xffffff);
    return mb_encode_numericentity($string, $convmap, "UTF-8");
}

You can change the encoding if you are using anything different.

  • Fixed map range. Thanks to Artefacto.
查看更多
登录 后发表回答