【问题标题】:Reformat number inside array of string PHP重新格式化字符串 PHP 数组中的数字
【发布时间】:2023-03-28 09:18:02
【问题描述】:

我有一个包含如下字符串的数组:

$items = array(
  "Receive 10010 from John",
  "Send 1503000 to Jane",
  "Receive 589 from Andy",
  "Send 3454 to Mary"
);

我想重新格式化这个数组中的数字,让它变成这样:

$items = array(
  "Receive 10.010 from John",
  "Send 1.503.000 to Jane",
  "Receive 589 from Andy",
  "Send 3.454 to Mary"
);

如果我使用number_format 函数,它看起来像这样,带有数字变量:

$number = '412223';
number_format($number,0,',','.');
echo $number; //412.223

【问题讨论】:

    标签: php arrays regex number-formatting


    【解决方案1】:

    您可以使用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;
    

    从约翰那里收到 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);
    

    数组
    (
    [0] => 从约翰那里收到 10.010
    [1] => 发送 1.503.000 给 Jane
    [2] => 收到安迪的 589
    [3] => 将 3.454 发送给 Mary
    )

    【讨论】:

      【解决方案2】:

      你来了

      按照以下步骤操作

      1. 使用 foreach 遍历循环
      2. 使用 preg_match_all('!\d+!', $str, $matches); 提取数字
      3. 应用数字格式 number_format($matches[0],0,',','.');
      4. 更新数组项

      所以整个故事就是使用 preg_match_all('!\d+!', $str, $matches);并提取字符串编号。

      【讨论】:

        【解决方案3】:

        如果你不希望十进制数字,你也可以使用类似的东西

        $items = preg_replace('/\d\K(?=(?:\d{3})+\b)/', ".", $items);
        

        regex demo at regex101php demo at eval.in

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-15
          • 1970-01-01
          • 2011-02-20
          • 1970-01-01
          相关资源
          最近更新 更多