Validate characters only with letters and spaces (including accents)

1

How can I validate a string and accept only letters with or without accents and spaces? I read a bit about ctype_alpha , but it did not work with accented letters, even though I have set the configs to pt_br :

setlocale(LC_ALL, 'pt_BR', 'pt_BR.UTF-8', 'pt_BR.UTF-8', 'portuguese');
    
asked by anonymous 05.10.2016 / 08:44

1 answer

1

The function ctype_alpha only checks if the characters are in the A-Za-z range. One option is to use preg_match with the expression [\pL\s]+ to match only letters and spaces.

function validar($string) {
    return !!preg_match('|^[\pL\s]+$|u', $string);
}

var_dump(validar("joÃO Maria")); // true
var_dump(validar("joao12"));     // false
var_dump(validar("Joao"));       // true
var_dump(validar("J0ao"));       // false
var_dump(validar(" "));          // true

The !! before preg_match is used to return the Boolean result.

The u modifier in the regular expression is to treat string as UTF-8.

    
05.10.2016 / 15:00