Jump to content

preg match: allow spaces in only the middle not at the start or at the end?


onedumbcoder

Recommended Posts

~^\S.*\S$~

 

however... what is your goal for this?  Are you trying to kick back an error for invalid input or something?  If the overall goal of this is to receive the data w/out the spaces on the ends, don't make the user re-enter it; just trim it. 

 

Not everything has to kick back an error.  This is something unnecessary, like how when forms are programmed to kick back errors for improperly formatted phone numbers or dates.  There's no reason to make the user go through the effort to enter in something exactly right, like dashes instead of parenthesis or slashes, etc.. 

okay so that regex tells it to match if there is 1 letter or number at the beginning of the string, followed by one or more spaces, until end of string. 

 

~^[a-z0-9\s]+$~i 

 

This is what you need.  The regex itself will allow for spaces on the edges, but if you trim it either before or after, the rest of the regex will match what you want.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.