Last active
May 31, 2023 08:04
-
-
Save RadGH/31f16cd4705a2d8076021a9ad528f34f to your computer and use it in GitHub Desktop.
Convert a phone number into an HTML link
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create an HTML link using a phone number. | |
* Supports international numbers by preserving common symbols. | |
* Supports an optional extension displayed after the link. | |
* | |
* @param string $phone | |
* | |
* @return string | |
*/ | |
function get_phone_number_link( $phone ) { | |
// Check for an extension, split it from the phone number | |
if ( preg_match('/([0-9])[^0-9]*(extension|ext|x).*?([0-9\-|\/]+)\b/i', $phone, $matches) ) { | |
// Get extension to put after the link | |
$extension = ' ext. ' . $matches[3]; | |
// Remove the extension from the phone number | |
$pos = strpos( $phone, $matches[0] ); | |
$phone = substr( $phone, 0, $pos + 1 ); | |
}else{ | |
// No extension | |
$extension = ''; | |
} | |
// Get the digits | |
$number = preg_replace('/[^0-9]/i', '', $phone); // "(123) 456-7890 ext. 123" => "1234567890" | |
// Special formatting for USA | |
if (preg_match('/^(\+1|1)?([2-9]\d{2})([\d]{3})([\d]{4})$/i', $number, $matches)) { | |
// 555.123.1234 -> | |
// (555) 456-7890 -> | |
// = 1 (555) GET-LOST | |
$link = sprintf('tel:+1%d%d%d', $matches[2], $matches[3], $matches[4]); | |
$display = sprintf('1 (%d) %d-%d', $matches[2], $matches[3], $matches[4]); | |
} else { | |
// Other countries: | |
// Only allow numbers and these symbols | |
$link = 'tel:+' . $number; | |
$display = preg_replace('/[^0-9\(\)\-\. ]/', '', $phone ); | |
} | |
// Get an HTML link | |
return sprintf( | |
'<a href="%s" itemprop="telephone">%s</a>%s', | |
esc_attr($link), | |
esc_html($display), | |
esc_html($extension) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment