View All Posts

Convert Alphanumeric Phone Numbers into Numeric

What do you do when you want to link phone numbers that use letters. One way is to manually convert each number every time a number is entered. Obviously this is not practical. So here is a PHP script to automatically make this happen. This code can be tweaked for international numbers.

The Number I used for this example is 800-455-BUGS

<?php 
$input = strtolower('800-455-BUGS');
$phone = strtr($input,'abcdefghijklmnopqrstuvwxyz', '22233344455566677778889999');

$cleannum = preg_replace('/[^A-Za-z0-9]/',"",$phone);
$formattednum = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1$2$3", $cleannum);

?>
Linked: <a href="tel:+1<?php echo $formattednum ?>">800-455-BUGS</a>

Result: <a href="tel:+18004552847">800-455-BUGS</a>

You can see it in action here: http://sandbox.onlinephpfunctions.com/code/2a9316d98325bc5bfff4e9b615fac375543d2ffa

This method will work with PHP 5.2.16 and higher.

 

Posted: August 5th, 2016
Updated: September 2nd, 2016

Category: Development
Tags: