开发者

Identifying international phone numbers in string in PHP

开发者 https://www.devze.com 2023-03-13 02:22 出处:网络
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 a

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 开发者_StackOverflow中文版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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消