how to make preg_match accept - or ( )

When insert phone number users tend to type in various way like 083-XXXXXXX or (083)XXXXXXX or XXXXXXX. I mean the extension and the phone or sometimes just the phone. How to make preg_match() accept the -XXX or (XXX) then return the real phone? For example (083) 1234567 will be 1234567.

I used this method:

preg_match("/^[-0-9]{10,20}$/",$value); 
preg_replace("/(083-)/","",$value); 

But it seems only accept the 083-. I want it can accept either -083 or (083)

How can I do that?

Upvotes: 2

Views: 280

Answers (3)

Programmer.zip
Programmer.zip

Reputation: 809

This pattern will work:

~^(\(\d+\)|\d+\-)?\d{10,20}$~

This is the test script:

<?php

$pattern = ''; // the regexp
$input = ''; // the phone number

$valid = preg_match($pattern, $input) ? 'valid' : 'INVALID';

echo 'The number is ' . $valid; // it prints out valid if phone number accepts prints out INVALID if phone number rejects
?>

My pattern:

~^(\(\d+\)|\d+\-)?\d{10,20}$~

Mmm... Let's test it!

$pattern = '~^(\(\d+\)|\d+\-)?\d{10,20}$~';
$input = '(083)0123456789';

output: The number is valid

Next number...

$input = '0123456789';

output: The number is valid

Next:

$input = '083-0123456789';

output: The number is valid

Let's test an INVALID number to make sure it works correctly

$input = '083+0123456789';

output: The number is INVALID

Next Step: Removing The Prefix

Code:

echo preg_replace('~(\(\d+\)|\d+\-)~', '', $input);
// input:(083)0123456789 , output: 0123456789
// input: 0123456789, output: 0123456789 
// input: 083-0123456789, output: 0123456789 

Finished!

Upvotes: 0

revo
revo

Reputation: 48741

Having this pattern:

/(?:(?:\(\d+\))|(?:\d+-))(\d+)/g

will return the phone number without country/province code. See demo.

Upvotes: 0

atrepp
atrepp

Reputation: 2122

Here you are : $value = preg_replace('/^((?:\(\d+\)|\d+)[- ]?)?(\d+)$/', '$2', $value);

Upvotes: 1

Related Questions