Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP letters and spaces only validation

I'm validating my contact form using PHP and I've used the following code:

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

This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_s and that comes up with a fatal error.

Any help would be greatly appreciated

like image 768
Andy Buckle Avatar asked Mar 11 '13 18:03

Andy Buckle


People also ask

How do you check if a string contains only alphabets and spaces in PHP?

PHP | ctype_alpha() (Checks for alphabetic value) A ctype_alpha() function in PHP used to check all characters of a given string are alphabetic or not. If all characters are alphabetic then return True otherwise return False. Parameters Used: $text :- It is a mandatory parameter which specifies the string.


4 Answers

One for the UTF-8 world that 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 kind of letter character from any language
  • Space after the p{L} => matches spaces
  • + => Quantifier — matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

This will also match names like Björk Guðmundsdóttir as noted in a comment by Anthony Hatzopoulos above.

like image 138
Epiphany Avatar answered Oct 21 '22 04:10

Epiphany


Regex is overkill and will perform worse for such a simple task, consider using native string functions:

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

This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:

str_replace(array("\n", "\t", ' '), '', $name);
like image 25
Martin Avatar answered Oct 21 '22 03:10

Martin


ctype_alpha only checks for the letters [A-Za-z]

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

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

if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
   $errors[] = "Name must only contain letters!";
} 
like image 12
V_K Avatar answered Oct 21 '22 02:10

V_K


if (ctype_alpha(str_replace(' ', '', $name)) === false)  {
  $errors[] = 'Name must contain letters and spaces only';
}
like image 1
Jinia Avatar answered Oct 21 '22 03:10

Jinia