Regex to allow alphanumeric and dot

前端 未结 3 419
野趣味
野趣味 2020-12-11 21:15

Hi I have a variable in a Silex route and we only allow alphanumeric values

->assert(\'hash\',\'\\w+\')

I would like to also allow a dot

相关标签:
3条回答
  • 2020-12-11 21:23

    I don't know the internals of assert(), but use a char class:

    ->assert('hash','[\w.]+')
    
    0 讨论(0)
  • 2020-12-11 21:24

    Try using a character class ([…]), like this:

    [\w.]+
    

    For example:

    ->assert('hash','[\w.]+')
    
    0 讨论(0)
  • 2020-12-11 21:46

    Try

    ->assert('hash', '[a-zA-Z0-9.]+')
    

    Why not [\w.]?

    You tagged your question as PHP so I assume that this manual applies. And there it reads

    \w  
        any "word" character
    

    and

    A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

    So after all \w might match äöüß... you don't know.

    As it reads hash you may also want to try

    ->assert('hash', '[a-fA-F0-9.]+')
    

    which only accepts hex-digits and . and not G or Z or ...

    0 讨论(0)
提交回复
热议问题