How to modify a preg_match function to accept spaces

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

How to modify a preg_match function to accept spaces

Post by edawson003 »

How can I modify the below preg_match function to accept [letters][space][letters]. Want to still exclude numbers and other characters.

If it is easy, wouldn't mind excluding these entry options as well:
-[space][letters]
-[letters][space]
But, no big deal as I can trim those out when I post form.

Code: Select all

 
elseif(!preg_match("/^([a-zA-Z])+$/", $_POST['servingunits'])) {
     $reqverrors[] = "Yes";
     $errName = "\t<br><span class=pred>Units must be from letters and spaces.</span>\n";
     }
 

I tried this but it didn't work

Code: Select all

 
elseif(!preg_match("/^([a-zA-Z[color=#FF0000] ]) ([ a-zA-Z])[/color]+$/", $_POST['servingunits'])) {
     $reqverrors[] = "Yes";
     $errName = "\t<br><span class=pred>Units must be from letters and spaces.</span>\n";
     }
 
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How to modify a preg_match function to accept spaces

Post by Eric! »

Try the \s instead for a whitespace. See character classes:

http://www.zytrax.com/tech/web/regex.htm
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

Re: How to modify a preg_match function to accept spaces

Post by edawson003 »

Ok, trying to get it to work. Where do I place the \s?

:banghead:

I tried this:

Code: Select all

elseif(!preg_match("/^([a-zA-Z][color=#FF0000]\s[/color])+$/", $_POST['servingunits'])) {
I tried this:

Code: Select all

elseif(!preg_match("/^([a-zA-Z][color=#FF0000]+\s[/color])+$/", $_POST['servingunits'])) {
Post Reply