Reputation: 1054
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
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";
}
So you can understand a few things...
ereg()
has been deprecated as of PHP 5.3. Stop using it, and use preg_match()
.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. ~
$testCases = array(
'',
'abc',
'123',
'لإنجليزية',
'abc1',
'русский'
);
foreach($testCases as $str) {
echo '"' . $str . '" letters only? ' . var_export((bool) preg_match('/^\pL+$/u', $str), TRUE) . "\n";
}
"" letters only? false
"abc" letters only? true
"123" letters only? false
"لإنجليزية" letters only? true
"abc1" letters only? false
"русский" letters only? true
Upvotes: 14
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