将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;
}
本文介绍了几种在PHP中实现数字格式化的方法,包括使用正则表达式、number_format函数及自定义函数等,展示了如何将长数字串以千位分隔符的形式显示。
832

被折叠的 条评论
为什么被折叠?



