Search code examples
phpregexunicodepreg-match

Match Polish characters in PHP with preg_match


I am trying to do some server side validation in PHP. I tried hard but I found still no solution. I am trying to allow only Polish characters in the input.

For this I have used:

preg_match('/^[\x{0104}-\x{017c}]*$/u',$titles)

This doesn't work however.

Anyone has any idea how to write it properly?


Solution

  • To match Polish letters only, you just need a character class:

    [a-pr-uwy-zA-PR-UWY-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ]
    

    Use as

    preg_match('/^[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ]*$/iu',$titles)
    

    Note that there is no Q, V and X in Polish, but since they can be met in some words (taxi), you may want to allow these letters as well. Then, use '/^[A-ZĄĆĘŁŃÓŚŹŻ]*$/iu' regex.

    IDEONE demo

    if (preg_match('/^[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ]*$/iu', "spółka")) {
        echo "The whole string contains only Polish letters";
    }