In PHP, how do I check if a String contains only letters? I want to write an if statement that will return false if there is (white space, number, symbol) or anything else other than a-z and A-Z.
My string must contain ONLY letters.
I thought I could do it this way, but I’m doing it wrong:
if( ereg("[a-zA-Z]+", $myString))
return true;
else
return false;
How do I find out if myString contains only letters?
Never heard of
ereg, but I’d guess that it will match on substrings.In that case, you want to include anchors on either end of your regexp so as to force a match on the whole string:
Also, you could simplify your function to read
because the
ifto returntrueorfalsefrom what’s already a boolean is redundant.Alternatively, you could match on any character that’s not a letter, and return the complement of the result:
Note the
^at the beginning of the character set, which inverts it. Also note that you no longer need the+after it, as a single “bad” character will cause a match.Finally… this advice is for Java because you have a Java tag on your question. But the
$in$myStringmakes it look like you’re dealing with, maybe Perl or PHP? Some clarification might help.