views:

122

answers:

3

Hi,

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

+4  A: 

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 any of the characters are alphanumeric + comma.
  • /^[a-zA-Z0-9,]+$/ matches if all of the characters are alphanumeric + comma.
NullUserException
thank you so much!
lauthiamkok
+2  A: 
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.
codaddict
thank you so much!
lauthiamkok
A: 

Well this adds a couple more characters like underscore

/^[\w,]*$/

But this should work

/^[a-zA-Z0-9,]*$/
Phill Pafford
whitespace. How ?
codaddict
`\w` doesn't include whitespaces.
NullUserException
hmm thought the \w did whitespace as well but after looking it doesn't. Thanks guys learning everyday
Phill Pafford
thank you so much!
lauthiamkok