繁体   English   中英

使用正则表达式替换将电话号码转换为“ tel:”超链接

[英]Converting telephone numbers into “tel:” hyperlinks with regular expression replacement

我从数据库中提取了以下内容:

总机:265-7404-6,营销热线:265-7403,B'ce:333-6848

我想在PHP中将其转换为如下形式:

预期的数据格式

如果扩展名为: 265-7404-6则仅解析: 265-7404

function printdir()
{
   $mysqli = new mysqli(constant("host"),constant("username"),constant("password"), constant("database"));

   $storedProc = "SELECT * FROM `directory`;";
   $result = $mysqli->query($storedProc);

   if($mysqli->affected_rows>0)
   {
       while( $row = $result->fetch_assoc()) {
          echo $row['telephone']; /*Formatting here*/
       }
   }
}

$telnumber = explode('-', $row['telephone'], 3));

echo $telnumber[0].'-'.$telnumber[1];

扩展名和第二个值之后的任何内容都将在$ telnumber [2]中

    <?php

function format_number($phone){
    $phone = preg_replace("#[^\d{10}\s]#",'',$phone);
    if(strlen($phone)==7)
        {
         $area = substr($phone,0,3);
    $prefix = substr($phone,3,4);

    $format = $area."-".$prefix;
    $phone = "<a href=\"tel:".$format."\">$format</a>";
    return($phone);
        }
     if(strlen($phone) != 10) return(False);
    $area = substr($phone,0,3);
    $prefix = substr($phone,3,3);
    $number = substr($phone,6,4);
    $format = $area."-".$prefix."-".$number;
    $phone = "<a href=\"tel:".$format."\">$format</a>";
    return($phone);
}

function telephoneText($string)
{
$format_one.= '\d{10}'; //5085551234

$format_two_and_three .= '\d{3}(\.|\-)\d{3}\2\d{4}'; //508.555.1234 or 508-555-1234

$format_four .= '\(\d{3}\)\-\d{3}\-\d{4}'; //(508)-555-1234

$format_five .='\d{3}\-\d{4}'; //(508)555-1234

$format_five_seven .='\d{7}';
$string = preg_replace("~({$format_one}|{$format_two_and_three}|{$format_four}|{$format_five}|{$format_five_seven})~e", 'format_number("$1")', $string);

return $string;
}



?>

那就是我想要达到的目标。 多谢你们..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM