PHP regular expression. Check if a string contains ONLY letters

In PHP, how to check if a string contains only letters? I want to write if an expression that will return false, if any (white space, number, symbol) or anything other than a-z

and a-z

.

My string should contain ONLY letters.

I thought I could do it like this, but I'm doing it wrong:

if( ereg("[a-zA-Z]+", $myString))
   return true;
else
   return false;

      

How do you know if it contains myString

only letters?

+2


a source to share


6 answers


Never heard of ereg

, but I would assume it would match substrings.

In this case, you want to include anchors at either end of your regex to force a match across the entire string:

"^[a-zA-Z]+$"

      

Also, you can simplify your read function

return ereg("^[a-zA-Z]+$", $myString);

      

because it if

returns true

or false

from what is already boolean is redundant.




Alternatively, you can match any character, not a letter, and return the complement to the result:

return !ereg("[^a-zA-Z]", $myString);

      

Notice at ^

the beginning of the character set that inverts it. Also note that you will no longer need it +

after one bad character causes a match.


Finally ... this tip is for Java, because you have a tag Javafor your question. But $

to $myString

make it look as if you are dealing with Perl or PHP? Some clarification might help.

+8


a source


Yes, it works great. Thanks to



if(myString.matches("^[a-zA-Z]+$"))

      

+10


a source


Your code looks like PHP

. It will return true

if the string contains a letter. To make a string only have letters, you need to use start and end anchors :

In Java

you can use a matches

class method String

:

boolean hasOnlyLetters(String str) {
   return str.matches("^[a-zA-Z]+$");
}

      

The PHP

function is ereg

now deprecated . You must use preg_match

as a replacement. PHP

equivalent of the above function:

function hasOnlyLetters($str) {
   return preg_match('/^[a-z]+$/i',$str);
}

      

+4


a source


I'm going to be different and defining what a letter is. Character.isLetter

if (myString.matches("\\p{javaLetter}*"))

      

Note that this is not only true [A-Za-z]*

.

A character is considered a letter if its generic category type provided Character.getType(ch)

is any of the following: UPPERCASE_LETTER, LOWERCASE_LETTER, TITLECASE_LETTER, MODIFIER_LETTER, OTHER_LETTER

Not all letters have a case. Many characters are letters, but not uppercase, lowercase, or uppercase.

Character classes are \p{javaXXX}

defined in the Pattern

API
.

+3


a source


Alternatively, try checking if it contains anything other than letters: [^ A-Za-z]

0


a source


The easiest way to make "ALL characters of a given type" is to check if ANY character is of the WRONG type.

So, if \ W stands for non-character, then just check one of them.

0


a source







All Articles