syrkull
syrkull

Reputation: 2344

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

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?

Upvotes: 5

Views: 1769

Answers (2)

cleong
cleong

Reputation: 7606

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

<?php

$s = "محمد";

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

echo $m[0];

?>

Upvotes: 4

zerkms
zerkms

Reputation: 254886

Use mb_substr:

$str = 'محمد';

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

Online demo

Upvotes: 13

Related Questions