Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the first letter in a string (the string contains arabic letters)

Tags:

php

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?

like image 866
syrkull Avatar asked May 24 '13 23:05

syrkull


People also ask

How do I check if a string contains an Arabic character?

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.

What is the first letter of the alphabet in 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.

How do I know if a string is Arabic or English?

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.


2 Answers

Use mb_substr:

$str = 'محمد';

var_dump(mb_substr($str, 0, 1, 'utf8')); // string(2) "م"

Online demo

like image 143
zerkms Avatar answered Oct 07 '22 00:10

zerkms


If you don't have mbstring installed, you can use preg_match():

<?php

$s = "محمد";

preg_match("/./u", $s, $m);

echo $m[0];

?>
like image 36
cleong Avatar answered Oct 07 '22 00:10

cleong