18

I would like to validate a string with a pattern that can only contain letters (including letters with accents). Here is the code I use and it always returns "nok". I don't know what I am doing wrong, can you help? thanks

$string = 'é';

if(preg_match('/^[\p{L}]+$/i', $string)){

    echo 'ok';

} else{

    echo 'nok';
}
Vincent
  • 1,651
  • 9
  • 28
  • 54

2 Answers2

47

Add the UTF-8 modifier flag (u) to your expression:

/^\p{L}+$/ui

There is also no need to wrap \p{L} inside of a character class.

  • 1
    Thank you! This was driving me crazy, trying to get an expression like `/état(.*)/i` trying to match "États-unis" and "états-unis"... – Rémi Breton Jan 27 '15 at 15:07
1

I don't know if this helps anybody that will check this question / thread later. The code below allows only letters, accents and spaces. No symbols or punctuation like .,?/>[-< etc.

<?php
$string = 'États unis and états unis';

if(preg_match('/^[a-zA-Z \p{L}]+$/ui', $string)){

echo 'ok';

} else{

echo 'nok';
}

?>

If you want to add numbers too, just add 0-9 immediately after Z like this a-zA-Z0-9

Then if you are applying this to form validation and you are scared a client/user might just hit spacebar and submit, just use:

if (trim($_POST['forminput']) == "") {... some error message ...}

to reject the submission.

Chimdi
  • 303
  • 2
  • 7
  • FYI: `[a-zA-Z]` is already included in `\p{L}` and the `/i` flag is useless here. And the question is about letters only, no spaces, punctuations, digits ... – Toto Apr 01 '20 at 17:21