I am trying to retrieve the first letter of a string. My current simple function is :
function idar($word)
{
return substr($word, 0, 1);
}
However, I realized that this function does not work on Arabic letters! It returns nothing to me.
for example try the word "محمد" it suppose to return "م" as the first letter.
Is there another way of returning the first letter of a string of any language?
https://www.npmjs.com/package/is-arabic It checks both Arabic and Farsi letters and Unicode as well. It also checks for Arabic symbols, Harakat, and numbers. You can also make it check for a certain number of characters.By default it checks if the whole string is Arabic.
Although usually considered to be the first letter of the Arabic alphabet, the small hamza (ء (ʾ)) that sits on top of أ (ʾ) is really the first letter of the Arabic alphabet, and the tall column is its bearer.
You can usually tell by the code points within the string itself. Arabic occupies certain blocks in the Unicode code space. It's a fairly safe bet that, if a substantial proportion of the characters exist in those blocks (such as بلدي الحوامات مليء الثعابينة ), it's Arabic text.
Use mb_substr
:
$str = 'محمد';
var_dump(mb_substr($str, 0, 1, 'utf8')); // string(2) "م"
Online demo
If you don't have mbstring installed, you can use preg_match():
<?php
$s = "محمد";
preg_match("/./u", $s, $m);
echo $m[0];
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With