Page 1 of 1
How to use white space?
Posted: Mon Sep 07, 2009 6:20 am
by Jeyush
Hi mate,
I use regex for my validation but @ this time I get confuse, how to use white space in it.
I want user to enter a city name, some city name contains white space like Los Angeles, New York, I have regex which is not allowing user to enter digits with city name.
like,
Code: Select all
if(ereg('[^A-Za-z]', $city)) {
echo "Only Characters Allowed";
}
else {
echo "Thank You";
}
But it is now allowing me to enter 'white space'. If you have some solution then please take me out of it.
Cheers!!!
Re: How to use white space?
Posted: Mon Sep 07, 2009 10:22 am
by jackpf
\s is the white-space character. Put that in there and it should accept it.
Re: How to use white space?
Posted: Mon Sep 07, 2009 12:04 pm
by ridgerunner
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
Re: How to use white space?
Posted: Mon Sep 07, 2009 12:07 pm
by jackpf
Ridgerunner...you're a regex god. Seriously.
Re: How to use white space?
Posted: Mon Sep 07, 2009 12:29 pm
by ridgerunner
jackpf wrote:Ridgerunner...you're a regex god. Seriously.
No, but I do aspire to becoming a disciple of Jeffrey Friedl (one of the the true masters). My addiction to regex came as a direct result from studying his classic:
Mastering Regular Expressions - 3rd Edition. I'm hooked and love to practice every chance I get.
Re: How to use white space?
Posted: Mon Sep 07, 2009 12:37 pm
by jackpf
That's pretty cool. Well...you're still a god in my eyes

Re: How to use white space?
Posted: Mon Sep 07, 2009 1:00 pm
by Eric!
I think this would work too and uses the more recent preg_match routines. I'm not very good with regex though.... It starts at the beginning of the string and looks for characters or spaces to the end anything else is not a match.
Code: Select all
if (preg_match('/^[a-zA-Z\s]+$/',$city))
{
echo "Thank You";
}
else
{
echo "Only Characters Allowed";
}