preg_match: number-alphabets and commas only

前端 未结 3 966
暖寄归人
暖寄归人 2020-12-30 12:19

How do I write a regular expression which matches number-alphabets and commas only?

I came out with this one below but it doesnt work - it accepts other punctuation

3条回答
  •  猫巷女王i
    2020-12-30 12:52

    if(preg_match('/^[0-9a-z,]+$/i', $cst_value)) {
      // valid input..contains only alphabet,number and comma.
    }else{
      // invalid
    }
    

    We pass the following to preg_match : /^[0-9a-z,]+$/i

    Explanation:

    • / : regex delimiters.
    • ^ : start anchor
    • [..] : Char class
    • 0-9 : any digit
    • a-z : any alphabet
    • , : a comma. comma is not a regex metachar, so you need not escape it
    • + : quantifier for one or more. If an empty input is considered valid, change + to *
    • $ : end anchor
    • i : to make the matching case insensitive.

提交回复
热议问题