2011-03-10 61 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'); 
?> 
相关问题