How do I allow spaces in this regex?

前端 未结 6 1235
渐次进展
渐次进展 2021-01-12 02:05

I\'m such an amateur at regex, how do I allow spaces(doesn\'t matter how many) in this regex?

if(preg_match(\'/[^A-Za-z0-9_-]/\', $str)) return FALSE;
         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 02:43

    You only need to add a literal blank space in your negated character class.

    It would be more concise to use:

    • the case-insensitive flag i and omit one of the letter ranges
    • and write [0-9] as \d

    like this:

    if (preg_match('/[^A-Z0-9_ -]/i', $str)) return FALSE;
    

    but even better would be to use \w which represents [A-Za-z0-9_] (which is most of your pattern) to write:

    if (preg_match('/[^\w -]/', $str)) return FALSE;
    

    This pattern states that if $str contains any character not in [A-Za-z0-9_ -] then false will be returned.

提交回复
热议问题