将1234567890转换成1,234,567,890 每3位用逗号隔开的形式
1.使用正则表达式解决!
//将1234567890转换成1,234,567,890 每3位用逗号隔开的形式。
$str1 = "1234567890000";
preg_match('/^(/d{1,3})((/d{3})+)$/',$str1,$out);
echo '<pre>';
print_r($out);
echo '</pre>';
$new_str = preg_replace('/^(/d{1,3})((/d{3})+)$/','$1,$2',$str1);
print $new_str."/n";
$new_str = preg_replace('/(?<=/d{3})(/d{3})/',',$1',$new_str);
print $new_str."/n";
exit;
2.用PHP系统函数number_format解决!
$s = 77843229987422200;
echo number_format($s);
3.用PHP自带的函数解决
$s = '77843229987422200';
$count = 4;
echo $s;
echo '<br>';
echo test($s,$count);
function test($s='',$count=3){
if(empty($s) || $count <= 0){
return false;
}
//反转
$str = strrev($s);
//分割
$arr = str_split($str,$count);
//连接
$new_s = join(',',$arr);
//再次反转
return strrev($new_s);
}
4.还有一种笨方法
function getString($str,$num,$sep)
{
$temp = strrev($str);
$arr = str_split($temp,$num);
$length = count($arr);
$temp = "";
for($i=$length-1;$i>=0;$i--)
{
if($i>0)
$temp=$temp.strrev($arr[$i]).$sep;
else
$temp=$temp.strrev($arr[$i]);
}
return $temp;
}