preg_match:仅数字字母和逗号 [英] preg_match: number-alphabets and commas only

查看:59
本文介绍了preg_match:仅数字字母和逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

非常感谢,刘

推荐答案

您想要:

/^[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,]+/ 如果任何字符是字母数字+逗号,则匹配.
  • /^[a-zA-Z0-9,]+$/ 匹配所有的字符是字母数字+逗号.
  • /[a-zA-Z0-9,]+/ matches if any of the characters are alphanumeric + comma.
  • /^[a-zA-Z0-9,]+$/ matches if all of the characters are alphanumeric + comma.

这篇关于preg_match:仅数字字母和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆