Reputation: 119
I write code that work only with english letters. when I ctry to do it with hebrew letter I get error.
the code:
<?php
$idan="emr";
$firstletter = mb_substr($idan, 0, 1, 'UTF-8');
if ($firstletter=='e')
echo "tov";
else echo "lo tove";
?>
work good. but the code:
<?php
$idan="אבהבה";
$firstletter = mb_substr($idan, 0, 1, 'UTF-8');
if ($firstletter=='א')
echo "tov";
else echo "lo tove";
?>
not work, How I can to fix it?
Upvotes: 2
Views: 403
Reputation:
Your code worked correctly (e.g. printed tov
) when I saved it to a PHP file and ran it. If you are seeing different results, you may want to check your text editor settings and ensure that you're saving the file as UTF-8.
Upvotes: 1
Reputation: 7773
You do realize that mb_substr
works from left to right? (is Hebrew written from right to left?) You are therefore reading the first character which is ה
not א
. To get the first letter from the right (the last one), use -1
as a starting index:
$firstletter = mb_substr($idan, -1, 1, 'UTF-8');
You can also use mb_internal_encoding("UTF-8");
to set the encoding for every call, instead of propagating it (if you're making many calls to mb_
functions)
Edit: Following your comments, here's a quick example of a script that handles letters depending on the language:
$desiredLetter = 'e';
$startIndex = 0;
// some condition to figure out the language
if(mb_detect_encoding($idan, 'ASCII', true) == FALSE)
{
$desiredLetter = 'א';
$startIndex = -1;
}
$firstletter = mb_substr($idan, $startIndex, 1, 'UTF-8');
if ($firstletter == $desiredLetter)
echo "tov";
else
echo "lo tove";
Upvotes: 3