Search code examples
phppreg-matchcharacterspecial-characters

php preg_match characters


I need help with preg_match function in php. I have read a lot of answers on SO, but I can't get any needed information.

So, I would like that preg_match check for characters a-z, A-Z, 0-9, special characters č, š, ž, đ, ć, Č, Š, Ž, Đ, Ć and ! " # $ % & / ( ) = ? * ° ' + - * . , - _ ; :

For first part (a-z, A-Z, 0-9) I saw how it is done, but for next part I don't have idea.


Solution

  • Simply list all characters in a character class:

    [a-zA-Z0-9čšžđćČŠŽĐĆ!"#$%&/()=?*°'+*.,_;:-]
    

    Since the minus sign bears special semantics, I moved it to the end where it, well, doesn't have special semantics. Make sure your editor encoding matches the input encoding (i.e. use UTF-8 everywhere).

    By the way, that list is really excessive. You may want to simply use \w, which stands for an arbitrary word character, or \S (anything but whitespace).