There are several problems with your method. First off the character class '[^A-Za-z]' matches only one single character. It is also not anchored to the beginning and end of the string. Here is a regex that will match one or more alpha-only words separated by a single space:
Code: Select all
if (ereg('^[A-Za-z]+( [A-Za-z]+)*$', $subject)) {
echo "Thank You";
} else {
echo "Only words separated by a single space allowed";
}
Here's a breakdown: The '^' matches the position at the beginning of the string. The '[A-Za-z]+' matches the first word - i.e. one or more alpha characters. The '( [A-Za-z]+)*' matches zero or more of a group which contains one single space followed by another word. And finally, the '$' matches the end of the string.
And note that the POSIX style
ereg functions have been superceded by the
preg functions which implement the much more powerful perl style regular expressions. If you are interested in learning a bit more about regular expressions, I recommend looking at the tutorial at
http://www.regular-expressions.info/. But be warned, regular expressions can be addictive!
Cheers