php preg_match:仅数字字母和逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3787495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:06:54  来源:igfitidea点击:

preg_match: number-alphabets and commas only

phpregexpreg-match

提问by laukok

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 marks as well!

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

# 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."/>';
  }

Many thanks, Lau

非常感谢,刘

回答by NullUserException

You want:

你要:

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

You need the start ^and end $of string anchors. Without them the regex engine will look for any of those characters in the string and if it finds one, it will call it a day and say there's a match. With the anchors, it forces the engine to look at the whole string. Basically:

您需要字符串锚点的开头^和结尾$。如果没有它们,正则表达式引擎将在字符串中查找这些字符中的任何一个,如果找到一个,它将称它为一天并说有一个匹配项。使用锚点,它会强制引擎查看整个字符串。基本上:

  • /[a-zA-Z0-9,]+/matches if anyof the characters are alphanumeric + comma.
  • /^[a-zA-Z0-9,]+$/matches if allof the characters are alphanumeric + comma.
  • /[a-zA-Z0-9,]+/如果任何字符是字母数字 + 逗号,则匹配。
  • /^[a-zA-Z0-9,]+$/如果所有字符都是字母数字 + 逗号,则匹配。

回答by codaddict

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

我们将以下内容传递给 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.
  • /: 正则表达式分隔符。
  • ^: 开始锚
  • [..]: 字符类
  • 0-9: 任何数字
  • a-z: 任何字母
  • ,: 逗号。逗号不是正则表达式元字符,因此您无需对其进行转义
  • +: 一个或多个的量词。如果认为空输入有效,则更+改为*
  • $: 结束锚
  • i: 使匹配不区分大小写。

回答by Phill Pafford

Well this adds a couple more characters like underscore

嗯,这增加了几个字符,比如下划线

/^[\w,]*$/

/^[\w,]*$/

But this should work

但这应该有效

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