How can I check whether a character is a Unicode character or not with PHP?
You'd usually do something like:
if (mb_strlen($ch) != strlen($ch)) ...
I should add: strlen counts bytes, while mb_strlen counts characters (properly handling multi-byte characters, which I guess is what you're really talking about rather than unicode - as unicode also covers over a hundred single-byte characters indistinguishable from ASCII)
(PHP 6 >= 6.0.0) is_unicode()
<?php
/*** create a unicode string ***/
$unicode = "ûПÌčöđę";
/*** check if value is unicode ***/
if(is_unicode($unicode))
{
echo 'Unicode string';
}
?>
Hi Searlea,
Ive checked this with this code :
<?php
$ch = 'രവീഷ്'; // my name in Malayalam
echo mb_strlen($ch)."<br/>";
echo strlen($ch)."<br/>";
if (mb_strlen($ch) != strlen($ch))
echo "Unicode";
else
echo "Non-Unicode";
?>
and i am getting the result like :
15
15
Non-unicode
that means strlen and mb_strlen returns the same result. what could be the error ?
A unicode character will ALWAYS have the most significant byte set no matter what the value of the character is or if it's part of a multi-byte unicode character or what. You can't just check to see if the string has more bytes than characters since some unicode characters are only one byte. If any character in a string's byte value is greater than 127, that string contains unicode.
Actually you don't even need the mb_string extension:
if (strlen($string) != strlen(utf8_decode($string)))
{
echo 'is unicode';
}
And to find the code point of a given character:
$ord = unpack('N', mb_convert_encoding($string, 'UCS-4BE', 'UTF-8'));
echo $ord[1];
Thanks for all these valuable comments!! thanks for the patience to explain the basics to a newbie like me..
Can anyone suggest a way to get the code point of a Unicode character ?
Thanks guys .. Finally i got the answer i was looking for .
Got an include file from http://hsivonen.iki.fi/php-utf8/.
The following code solved my problem:
<?php
require_once("utf8.inc");
/*** create a unicode string ***/
$s = "حملة إلا صلاتي";
$out = utf8ToUnicode($s);
for ($i=0;$i < strlen($s);$i++)
echo dechex($out[$i]).".";
?>
Strings in PHP are bytestreams - not character streams. You can't actually have unicode strings in PHP; You need to encode your characters with some encoding. If you want to cover the entire unicode range, UTF-8 is the most obvious choice.
If you want to get the codepoint of a utf-8 encoded bytestream, you can use this library: http://hsivonen.iki.fi/php-utf8/
However, I wonder what exactly you need this for? Most likely, you can solve all your woes by simply using utf-8.