I was playing with a basic function and wondered if the below was a particularly efficient method to convert from plain text to a clickable tel link?
The function would be assuming the following plain text scenarios:
Here's the function:
function pd_convert_tel_number($tel) {
if (substr( $tel, 0, 1 ) === '0') {
$tel = '<a href="tel:+44'.ltrim(str_replace(' ', '', $tel), '0').'">'.$tel.'</a>';
} else if(strpos($tel, '+44') !== false || strpos($tel, '(0)') !== false) {
$tel = '<a href="tel:'.str_replace(array( '(0)', ' ' ), '', $tel).'">'.$tel.'</a>';
} else {
$tel = '<a href="tel:"'.$tel.'">'.$tel.'</a>';
}
return $tel;
}
I would have made a function that is just formating phone number properly (without adding <a></a>
. Then I would just add the link with the formatted phone number. But if your function works, it doesn't seems too bad.
You can use regex.
This adds the a href tag to the phonneumber.
https://regex101.com/r/vT9phL/1
$re = '/^(0|\+44)(.*)/m';
$str = '01234 123 456
+44 1234 123 456
+44 (0) 1234 123 456';
$subst = '<a href="tel:+44 $2>$2</a>';
$result = preg_replace($re, $subst, $str);
echo $result;
The pattern will match "0" or +44 at the start of string and "delete it" then add the href.