PHP function chr of unicode character


PHP have function chr to find a character from a ASCII value. But PHP don’t support a function to find this with unicode character. Now, we provider some method, they are equivalent with String.fromCharCode() in Javascript:

/**
 * @author www.Tutorialspots.com
 * @copyright 2017
 */

function unichr($dec) {
	if ($dec < 128) {
	   $utf = chr($dec);
	}
	elseif ($dec < 2048){
    	$utf = chr(192 + (($dec - ($dec % 64)) / 64));
    	$utf .= chr(128 + ($dec % 64));
	}
	else{
    	$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
    	$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
    	$utf .= chr(128 + ($dec % 64));
	}
    return $utf;
}

function unichr2() {
    $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

function unichr3($dec)
{
  if ($dec < 0x80)
  {
    $utf = chr($dec);
  }
  else if ($dec < 0x0800)
  {
    $utf = chr(0xC0 + ($dec >> 6));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else if ($dec < 0x010000)
  {
    $utf = chr(0xE0 + ($dec >> 12));
    $utf .= chr(0x80 + (($dec >> 6) & 0x3f));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else if ($dec < 0x200000)
  {
    $utf = chr(0xF0 + ($dec >> 18));
    $utf .= chr(0x80 + (($dec >> 12) & 0x3f));
    $utf .= chr(0x80 + (($dec >> 6) & 0x3f));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else return false;

  return $utf;
}

function unichr4($u) {
    return mb_convert_encoding(pack("N",$u), 'UTF8', 'UCS-4BE');
}

Examples:

echo unichr(9829);//♥
echo "<br />";
echo unichr2(10085);//❥
echo "<br />";
echo unichr3(10086);//❦
echo "<br />";
echo unichr4(10087);//❧
echo "<br />";

2 Comments

Leave a Reply