She*_*ite 10 php regex arrays number-formatting
我有一个包含这样的字符串的数组:
$items = array(
"Receive 10010 from John",
"Send 1503000 to Jane",
"Receive 589 from Andy",
"Send 3454 to Mary"
);
Run Code Online (Sandbox Code Playgroud)
我想重新格式化这个数组中的数字,所以它将变成这样:
$items = array(
"Receive 10.010 from John",
"Send 1.503.000 to Jane",
"Receive 589 from Andy",
"Send 3.454 to Mary"
);
Run Code Online (Sandbox Code Playgroud)
如果我使用number_format函数,它将看起来像数字varibale:
$number = '412223';
number_format($number,0,',','.');
echo $number; //412.223
Run Code Online (Sandbox Code Playgroud)
您可以使用preg_replace_callback匹配字符串中的数字并应用一些自定义格式.对于单个字符串,这将如下所示:
$string = "Receive 10010 from John";
$formatted = preg_replace_callback( "/[0-9]+/", function ($matches) {
return number_format($matches[0], 0, ',', '.');
}, $string);
echo $formatted;
Run Code Online (Sandbox Code Playgroud)
从John收到10.010
如果要将相同的逻辑应用于整个数组,可以将以上内容包装在以下内容中array_map:
$formatted = array_map(function ($string) {
return preg_replace_callback( "/[0-9]+/", function ($matches) {
return number_format($matches[0], 0, ',', '.');
}, $string);
}, $items);
print_r($formatted);
Run Code Online (Sandbox Code Playgroud)
数组
(
[0] =>从John
[1] 接收10.010 =>发送1.503.000到Jane
[2] =>从Andy接收589
[3] =>发送3.454到Mary
)
| 归档时间: |
|
| 查看次数: |
549 次 |
| 最近记录: |