Patrick
Patrick

Reputation: 3450

Identifying international phone numbers in string in PHP

I am trying to write a function that will pull valid phone numbers from a string that are valid somewhere on the planet. This is for a truly international site for an organization that has locations all over the globe and users in each location accessing it.

I mainly need this for a database migration. The previous sites that I am migrating from only used a simple text field with not instructions and no filtering. So this results in the phone fields being used in all sorts of creative ways.

What I am looking for it just to identify the first phone number in the string, then possibly remove any excessive characters before setting the result as user profile information.

Upvotes: 2

Views: 1928

Answers (3)

John Sheehan
John Sheehan

Reputation: 78104

There's a PHP port available of Google's Phone Number Library.

Upvotes: 5

ldg
ldg

Reputation: 9402

you could use something like this:

$pattern = '/([\+_\-\(\)a-z ]+)/';

or

$pattern = '/([^0-9]+)/i';

$phone = preg_replace($pattern,'', $phone);

or, use a php filter like:

$phone = (int) filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

although with the filter you would need to be careful if you were allowing the value to start with "0".

then, either way, check a range of lengths for allowed phone numbers ~6-12 or whatever your range covers.

Upvotes: 2

George Cummins
George Cummins

Reputation: 28906

First, you will need to compile a list of valid phone number formats.

Second, you will need to create regular expressions to identify each format.

Third, you will run the regexes against your text to locate the numbers.

Upvotes: 0

Related Questions