簡體   English   中英

在PHP中使用Regex格式化和替換電話號碼

[英]Format and replace a phone number using Regex in PHP

我正在嘗試在用戶注冊/編輯表單上驗證電話號碼。 有兩個字段:電話號碼1和電話號碼2。它們可能會填滿,也可能不會填滿。 如果它們滿了,我將必須提取其數字,並使用正則表達式正確設置其格式並顯示它,以便用戶進行編輯。 問題是我是一個初學者,並且無法對其進行格式化。 下面是代碼:

if (!empty($phone_1 )) {
    $string = $phone_1;
    $newString = preg_replace('/[^0-9]/i', '', $string); //extract numbers

    $regex = '^(11 [9][0-9]{4}-[0-9]{4})|(\(1[2-9]\) [5-9][0-9]{3}-[0-9]{4})|(\      ([2-9][1-9]\) [5-9][0-9]{3}-[0-9]{4})$';
    $final = preg_replace($regex, '', $newString);
  }

我嘗試輸出的格式是“ 99 99999.9999”。

謝謝。

為什么不使用sub_str格式化字符串?

$phone1="01234567890";
$phone1 = substr($phone1, 0, 2) . ' ' . substr($phone1, 2, 5) . '.' . substr($phone1, 7, 4);
echo $phone1;

輸出:

01 23456.7890

如果要使用正則表達式,可以使用以下命令:

^(\d\d)(\d{5})(\d{4})$

工作演示

在此處輸入圖片說明

您可以使用的代碼是:

$re = "/^(\\d\\d)(\\d{5})(\\d{4})$/"; 
$str = "01234567890"; 
$subst = '\1 \2.\3'; 

$result = preg_replace($re, $subst, $str, 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM