-1

This snippet of code is taken from codeigniter and i'm trying to copy it into a new function that allows numeric characters and dashes. What do i need to add to this regex to allow dashes and parenthesis as well?

preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
Catfish
  • 18,876
  • 54
  • 209
  • 353
  • Add them to the character class? * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Nov 06 '12 at 04:23

2 Answers2

2

Your regular expression means this: Begin the line with a - or + MAYBE Then 0-9 zero or more times Then a . MAYBE Then end with AT LEAST ONE of the following numbers: 0-9

You need to specify what you want the RegEx to do, then someone can write a correct RegEx.

EDIT Here you go:

<?php

// 555-555-5555 or (555) 555-5555 or (555)555-5555
$str = '555-555-5555';
if (preg_match( '/^((\([0-9]{3}\)) ?|[0-9]{3}-)[0-9]{3}-[0-9]{4}$/', $str) == 1){
    echo 'Yes!';
}else{
    echo 'No!';
}
?>
keyboardSmasher
  • 2,661
  • 18
  • 20
  • The code posted in the question was taken straight out of the codeigniter function "Numeric" in the form_validation class. I just wanted to add dashes and parenthesis to it so that they are allowed as well. – Catfish Nov 06 '12 at 05:30
  • @Catfish, The answer you marked correct allows `+- -)(0` Does that look like anyone's phone number? – keyboardSmasher Nov 06 '12 at 06:25
  • It's ok for my application because i strip anything but numbers to insert it into the database. It's just so people can enter a variety of formats. – Catfish Nov 06 '12 at 14:43
  • I'm guessing it allows `+` or `-` because the codeigniter `numeric` format must allow for numbers like `-2`, `+2`, etc. – Catfish Nov 06 '12 at 14:44
1
preg_match( '/^\+?[-0-9]*\.?[-0-9]+$/', $str);

update:

preg_match( '/^\+?[-0-9()]*\.?[-0-9()]+$/', $str);
nkamm
  • 627
  • 5
  • 14
  • I updated the question to allow parenthesis as well. Can you update your answer? – Catfish Nov 06 '12 at 04:18
  • Updated. Not sure at which place you are required in parenthesis though, some examples of `$str` would rock. – nkamm Nov 06 '12 at 04:23
  • I'm trying to allow users to enter a phone number in multiple formats including `555-555-5555` or `(555) 555-555`. – Catfish Nov 06 '12 at 04:26
  • Better to use this one then `preg_match('/^\+?[-0-9() ]+[0-9]{1}$/', trim($str))`. – nkamm Nov 06 '12 at 04:38