How to convert all characters to their html entity equivalent using PHP

I want to convert this [email protected] 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....


Solution 1:

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

Solution 2:

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.

Solution 3:

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

}