0

i need to use a regular expression to validate a field with php that has to have two words separated by a space like: "First Last" but i cant find one that fits my purposes, can anyone help me?

The best i've done is ^[a-zA-Z0-9_\s]*$ but with this i can have more than one space and anywhere in the field and i want only between the words. Can anyone help me?

João Silva
  • 89,303
  • 29
  • 152
  • 158
Miguel Melo
  • 1
  • 1
  • 1

3 Answers3

9

Something like ^\w+\s\w+$ ought to work for this case. But you don't necessarily need to use regular expressions for this, you could just use explode().

Tim Martin
  • 3,618
  • 6
  • 32
  • 43
  • 1
    +1: Matches the OP's question exactly. But I would have upvoted you anyway, just for getting rid of that `{1}` abomination. :D – Alan Moore Feb 21 '11 at 03:17
4
^[^\s]+\s[^\s]+$
  • [^\s]+ matches one or more characters, except whitespace characters;
  • \s matches a single whitespace character.
João Silva
  • 89,303
  • 29
  • 152
  • 158
0

This might do the trick

^[a-zA-Z0-9]+ {1}[a-zA-Z0-9]+$
  • here works like this: ^\w+\s{1}\w+$ :P And if i want only letters A-Za-z instead of \w (alphanumeric)? I cant fit it to the regex :o – Miguel Melo Feb 20 '11 at 23:56
  • i have to put the \s but it's not serving my purpose, estrangely if i put a space in the beggining or at the end and only word it validates correctly :s ^[a-zA-Z0-9]+\s{1}[a-zA-Z0-9]+$ – Miguel Melo Feb 21 '11 at 00:07