0

I want to convert a string like:

alnassre 
will be 0061006c006e00610073007300720065
عربي
will be 063906310628064a
a
will be 0061

using PHP

as what is going in the link http://www.bareedsms.com/tools/UniCodeConverter.aspx

Mansour Alnasser
  • 4,446
  • 5
  • 40
  • 51

2 Answers2

3

I know you already found an answer that works for you, but this should be:

  1. Much faster

  2. Much easier to adapt to other character encodings.

It does depend on iconv, but all modern PHP installs have that, right?

 function utf8_to_unicode_codepoints($text) {
     return ''.implode(unpack('H*', iconv("UTF-8", "UCS-4BE", $text)));
 }
Daniel Martin
  • 23,083
  • 6
  • 50
  • 70
  • 1
    Note that this doesn't quite do what you asked! But that's because what you asked has issues (specifically, it won't work for all unicode characters since there are codepoints beyond 0xFFFF). To get close to what you asked for, use `UTF-16BE` or `UCS-2BE`. – Daniel Martin Dec 13 '13 at 20:41
1

I found the answer but it return array here

I Edit the function to return String.

function utf8_to_unicode($str) {

    $unicode = array();        
    $values = array();
    $lookingFor = 1;

    for ($i = 0; $i < strlen($str); $i++) {

        $thisValue = ord($str[$i]);

        if ($thisValue < 128) 
            $unicode[] = str_pad(dechex($thisValue), 4, "0", STR_PAD_LEFT);
        else {
            if (count($values) == 0) $lookingFor = ($thisValue < 224) ? 2 : 3;                
            $values[] = $thisValue;                
            if (count($values) == $lookingFor) {
                $number = ($lookingFor == 3) ?
                (($values[0] % 16) * 4096) + (($values[1] % 64) * 64) + ($values[2] % 64):
                (($values[0] % 32) * 64) + ($values[1] % 64);
                $number = strtoupper(dechex($number));
                $unicode[] = str_pad($number, 4, "0", STR_PAD_LEFT);
                $values = array();
                $lookingFor = 1;
            } // if
        } // if
    } // for
    $str="";
    foreach ($unicode as $key => $value) {
        $str .= $value;
    }


    return ($str);   
} // utf8_to_unicode
Community
  • 1
  • 1
Mansour Alnasser
  • 4,446
  • 5
  • 40
  • 51