1

How do i change any of the following to just numbers

1-(999)-999-9999 
1-999-999-9999
1-999-9999999
1(999)-999-9999
1(999)999-9999

i want the final product to be 19999999999

1

4 Answers 4

2

The easiest way would be to strip everything out of your string that's not a number and then see if you end up with a 10 digit number (or 11 if you're making the 1 mandatory):

$string = "1-(999)-999-9999";
$number = preg_replace('/[^0-9]/', "", $string); // results in 19999999999
if (strlen($number) == 11)
{
  // Probably have a phone number
}
0
2

try

preg_replace('\D', '', $string);

This will filter out any non digits.

0

You dont really need regex for this...

$number = str_replace(array('-', '(', ')'), '', $number);
2
  • what about things like x, ext, ., +, etc
    – CaffGeek
    Aug 10, 2010 at 15:19
  • If you know the input will be like one of the examples then thats all you need. If you dont know the input then you need more validation anyway.
    – OIS
    Aug 10, 2010 at 15:23
0
preg_replace('[\D*]', '', '1-(999)-999-9999');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.