将一个字符串(1234567890)转换成(1,234,567,890)每三个一组用逗号隔开
/**
* 方法1 php内置函数
*/
// $str = "1234567890";
// $newstr = number_format($str);
// echo $str;
// echo "<br/>";
// echo $newstr;
/**
* 方法2 php自带的函数实现
*/
$str = "1234567890"; //要格式化的数
$count = 3; //每几个数分割一次
echo $str;
echo "<br/>";
echo test($str,$count);
function test($str="",$count=3){
if(empty($str) || $count <= 0){
return false;
}
$str1 = strrev($str); //反转字符串
$arr = str_split($str1,$count); //将字符串分割成数组
$new_str = join(",",$arr); //连接字符串
return strrev($new_str); //再次反转字符串并返回
}
?>
用到的内置函数
number_format()
<?php
$number = 1234.56;
// english notation (default)
$english_format_number
= number_format
( $number );
// 1,235
// French notation
$nombre_format_francais
= number_format
( $number , 2,
"," ,
" ");
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number
= number_format
( $number , 2,
"." ,
"");
// 1234.57
?>
strrev()
返回 string
反转后的字符串。
<?php
echo strrev("Hello world!"); // 输出 "!dlrow olleH"
?>
implode() (别名join())
将一维数组的值连接为一个字符串
<?php
$array = array(
"lastname" , "email", "phone"
);
$comma_separated
= implode (",",
$array );
echo $comma_separated
; // lastname,email,phone
// Empty string when using an empty array:
var_dump (implode(
"hello" , array()));
// string(0) ""
?>
str_split()
- 上一篇:没有了
- 下一篇: 获取包含中英文的字符串的自然长度