PHP letters and spaces only validation

forms, php, validation

Solution

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);

Problem

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

Original source