0

I need a regex that would test if a word is composed of letters (alpha characters), white spaces, and periods (.). I need this to use for validating names that is entered in my database.

This is what I currently use:

preg_match('/^[\pL\s]+$/u',$foo)

It works fine for checking alpha characters and whitespaces, but rejects names with periods as well. I hope you guys can help as I have no idea how to use regex.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
christianleroy
  • 1,084
  • 5
  • 25
  • 39

3 Answers3

2

The following regex should satisfy your condition:

preg_match('/^[a-zA-Z\s.]+$/',$foo)
arco444
  • 22,002
  • 12
  • 63
  • 67
2

Add a dot to the character class so that it would match a literal dot also.

preg_match('/^[\p{L}.\s]+$/u',$foo)

OR

preg_match('/^[\pL.\s]+$/u',$foo)

Explanation:

  • ^ Asserts that we are at the start.
  • [\pL.\s]+ Matches any character in the list one or more times. \pL matches any Kind of letter from any language.
  • $ Asserts that we are at the end.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Thanks for the Edit; I was reading the regex and thinking "why on earth is he looking for an escaped `p` letter?" – MoshMage Sep 26 '14 at 08:43
2

In this link, you will find all the information you need to figure regex out with PHP. PHP Regex Cheat Sheet

Basically, if you want to add the period you add . :

preg_match('/^[\pL\s\.]+$/u',$foo)

Enjoy! :)

Softy
  • 111
  • 8