如何编写仅与数字字母和逗号匹配的正则表达式?

我在下面找到了这个,但是它不起作用-它也接受其他标点符号!

# check for matches number-alphabets and commas only
  if(!preg_match('/([a-zA-Z0-9]|[a-zA-Z0-9\,])/', $cst_value))
  {
   $error = true;
   echo '<error elementid="usr_username" message="'.$cst_name.' - please use number-alphabets and commas only."/>';
  }

非常感谢,

最佳答案

你要:

/^[a-zA-Z0-9,]+$/

您需要字符串 anchor 的开始^和结束$。如果没有它们,则正则表达式引擎将在字符串中查找这些字符中的任何一个,如果找到一个,则将其命名为“day”并表示存在匹配项。借助 anchor ,它迫使引擎查看整个琴弦。基本上:
  • /[a-zA-Z0-9,]+/如果任何字符是字母数字+逗号,则匹配。
  • 如果所有字符都是字母数字+逗号,则/^[a-zA-Z0-9,]+$/匹配。
  • 关于php - preg_match : number-alphabets and commas only,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3787495/

    10-13 00:33