php only allow letters, numbers, spaces and specific symbols using pregmatch

后端 未结 3 981

on my php i use preg_match to validate input texts.

if(preg_match(\'/^[a-zA-Z0-9]+$/\', $firstname)) {
}

But this only allows alp

3条回答
  •  野的像风
    2021-01-31 17:07

    The only difficult bit here is the dash.

    For spaces and dots, you can simply add them to your character class, like so:

    '/^[a-zA-Z0-9 .]+$/'
    

    Easy.

    The dash is slightly harder because hyphens have special meaning in a character class like this (as you already know, they're used for ranges of characters like a-z). In order to specify a hyphen in a character class, it must be the first character in the class (ie it must not be between two characters, otherwise it is treated as a character range marker).

    So your expression would be:

    '/^[-a-zA-Z0-9 .]+$/'
    

    Hope that helps.

提交回复
热议问题