Validating PHP letters and spaces only

I test my contact form with PHP and I used the following code:

if (ctype_alpha($name) === false) { $errors[] = 'Name must only contain letters!'; } 

This code works fine, but it checks and does not allow spaces. I tried ctype_alpha_s and this leads to a fatal error.

Any help would be greatly appreciated.

+4
source share
4 answers

Regex overkill and will work worse for such a simple task, consider using your own string functions:

 if (ctype_alpha(str_replace(' ', '', $name)) === false) { $errors[] = 'Name must contain letters and spaces only'; } 

This will result in a space bar before starting the alpha check. If tabs and newlines are a problem, you might think about this:

 str_replace(array("\n", "\t", ' '), '', $name); 
+16
source

ctype_alpha only checks letters [A-Za-z]

If you want to use it for your purpose, you will first need to remove the spaces from your string, and then apply ctype_alpha.

But I would go to preg_match to check for confirmation. You can do something like this.

 if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) { $errors[] = "Name must only contain letters!"; } 
+3
source
 if (ctype_alpha(str_replace(' ', '', $name)) === false) { $errors[] = 'Name must contain letters and spaces only'; } 
+1
source

One for the world of UTF-8, which will match spaces and letters from any language.

 if (!preg_match('/^[\p{L} ]+$/u', $name)){ $errors[] = 'Name must contain letters and spaces only!'; } 

Explanation:

  • [] => character class definition
  • p {L} => matches any letter character from any language
  • Space after space p {L} =>
  • + => Quantifier - matches from one to unlimited time (greedy)
  • / u => Unicode modifier. Template strings are treated as UTF-16. Also calls escape sequences to match Unicode characters

This will also match names such as Björk Guðmundsdóttir, as stated in Anthony Hatzopoulos's comment above.

0
source

All Articles