William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: 8 ways to convert 1234567890 to 1,234,567,890

Here I write 8 ways to convert 1234567890 to 1,234,567,890, all work fine.

<?php
// 1. preg_replace+RE:?<=
$str = “1234567890”;
$s1 = preg_replace(‘/^(\d{1,3})((\d{3})+)$/’,’$1,$2′,$str);
$s1 = preg_replace(‘/(?<=\d{3})(\d{3})/',',$1',$s1);
echo $s1 . "\n";

// 2. preg_replace
$s2 = preg_replace(“/(\d)(\d{3})(\d{3})(\d{3})/”, “$1,$2,$3,$4”, $str);
echo $s2 . “\n”;

// 3. str_split+str_replace
$str = “1234567890”;
$c = array();
if ((strlen($str) % 3) == 1) {
$str = ’00’.$str;
}
$c = str_split($str, 3);
$s5 = implode(‘,’,$c);
$s5 = str_replace(“00”, “”, $s5);
echo $s5 . “\n”;

// 4. array_unshift+intval
$a = array();
while (intval($str)>0) {
$str = intval($str) / 1000;
array_unshift($a, substr($str, strpos($str,’.’)+1, 3));
}
if(strlen($a[count($a)-1])!=3) {
$a[count($a)-1] .= ‘0’;
}
$s3 = implode(“,”, $a);
$s3 = preg_replace(“/^0+/”, ”, $s3);
echo $s3 . “\n”;

// 5. preg_match
$b = array();
$str = “1234567890”;
preg_match(“/(\d{1,3})(\d{3})(\d{3})(\d{3})$/”, $str, $b);
array_shift($b);
$s4 = join(‘,’, $b);
echo $s4 . “\n”;

// 6. substr_replace
$str = “1234567890”;
$t1 = substr_replace($str,’,’,-3,-3);
$t2 = substr_replace($t1,’,’,-7,-7);
$t3 = substr_replace($t2,’,’,-11,-11);
echo “$t3\n”;
?>

// 7. money_format

// 8. number_format

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: