2011-03-10 63 views
1

我需要將以下數字0825632332格式化爲此格式+27 (0)82 563 2332將特定輸入數字格式化爲其他格式

如果我使用正則表達式或普通字符串函數來執行重新格式化,哪種功能組合最好?如何?

+0

你想使用正則表達式來保持代碼的漂亮和乾淨。 – philipp 2011-06-28 02:04:54

回答

2

我想用正則表達式是最好的方式,也許是這樣的:

$text = preg_replace('/([0-9])([0-9]{2})([0-9]{3})([0-9]{4})/', '+27 ($1) $2 $3 $4', $num); 

注意,因爲你的電話號碼與0

您還可以使用啓動$ NUM必須是字符串字符類:

$text = preg_replace('/(\d)(\d{2})(\d{3})(\d{4})/', '+27 ($1) $2 $3 $4', $num); 
1

正則表達式將會很好地工作,更換

(\d)(\d{2})(\d{3})(\d{4}) 

通過

+27 (\1)\2 \3 \4 

您也可以執行字符串submatching如果你想。

2

既然你問 - 非正則表達式的解決方案:

<?php 
function phnum($s, $format = '+27 (.).. ... ....') { 
     $si = 0; 
     for ($i = 0; $i < strlen($format); $i++) 
       if ($format[$i] == '.') 
         $output[] = $s[$si++]; 
       else 
         $output[] = $format[$i]; 
     return join('',$output); 
} 

echo phnum('0825632332'); 
?> 
相關問題