簡體   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