Kareem Nour Emam
Kareem Nour Emam

Reputation: 1054

Regex to find only letters using PHP

I am trying to create a regex which will detect if a string has only letters in it. Can anyone tell me if the following code does that correctly?

$text = "asdsad";
if (ereg('[^A-Za-z]', $text)) {
  echo "More then letters";
}

else {
  echo "only letters";    
}

Upvotes: 1

Views: 10668

Answers (2)

alex
alex

Reputation: 490647

The condition evaluates to true, if that is what you meant.

You want to make sure a string has letters only?

Try this...

if (preg_match('/^\pL+$/u', $text)) {
   echo "Letters only";
} else {
   echo "More than letters";
}

See it on ideone.

So you can understand a few things...

  • ereg() has been deprecated as of PHP 5.3. Stop using it, and use preg_match().
  • When using a regex with preg_match(), you need to specify a regex delimiter. Most regex flavours use /, but PHP lets you use most matching pair of chars, e.g. ~
  • You are missing start and end anchors. This means you won't be matching the string from start to finish
  • Use Unicode regex where available, so non ASCII letters are still detected.

Update

Test cases.

PHP

$testCases = array(
    '',
    'abc',
    '123',
    'لإنجليزية',
    'abc1',
    'русский'
);

foreach($testCases as $str) {
    echo '"' . $str . '" letters only? ' . var_export((bool) preg_match('/^\pL+$/u', $str), TRUE) . "\n";
}

Output

"" letters only? false
"abc" letters only? true
"123" letters only? false
"لإنجليزية" letters only? true
"abc1" letters only? false
"русский" letters only? true

Upvotes: 14

Jacob
Jacob

Reputation: 8344

A better solution not using regular expression would be to use ctype_alpha

https://www.php.net/manual/en/function.ctype-alpha.php

As long as using the current locale, not just assuming the alphabet is a-zA-Z, is suitable.

Upvotes: 2

Related Questions