【问题标题】:add space after the third number except the last four numbers在第三个数字后添加空格,最后四个数字除外
【发布时间】:2021-10-22 21:58:33
【问题描述】:

我是 Laravel 的新手,我有一个小问题,那就是我在 DB 中有一个列,应该以特定的形式存储 13 个数字。 形式为除后四位数字外,每三位数字后加空格。

例如: 1234567891234 它应以以下格式存储: 123 456 789 1234

谢谢

【问题讨论】:

  • 将格式留给 larvel。如果它是数字,则在 mysql 中使用数字格式。它作为一个数字搜索对吗?欢迎来到 SO。

标签: php mysql laravel laravel-5


【解决方案1】:

如果您的数据库中此字段的列类型是数字,您将无法存储带有空格的值。

也就是说,回答你的问题:

$num = 1234567891234;

$iterations = (strlen($num) - 4) / 3;

for ($i = 0; $i < $iterations; $i++) {
    $parts[] = substr($num, $i * 3, 3);
}

$parts[] = substr($num, -4, 4);

$formatted = implode(' ', $parts);

【讨论】:

    【解决方案2】:

    您可以在不格式化的情况下存储该值,并在从数据库中检索该值时即时进行格式化。您可以通过以下代码实现。

    <?php
    $str = '1234567891234';
    $formatted_no = get_formatted_no($str);
    echo $formatted_no;
    
    function get_formatted_no($str){
        $re = '/(\w{3})(\w{3})(\w{3})(\w{4})/m';
        preg_match_all($re, $str, $matches);
        $matches = array_filter($matches, function($key){ return $key; }, ARRAY_FILTER_USE_KEY); 
        return array_reduce($matches, function($accumulator, $item) {
            return $accumulator .= $accumulator ? ' ' . current($item) : current($item); 
        }, '');
    }
    

    不过,何时进行格式化完全取决于您。您可以使用上面相同的代码在将字符串存储到数据库之前对其进行格式化,这样就无需在每次从数据库中检索到它时都对其进行格式化。不用说,您需要使用这种方法将 db 中的列类型更改为 varchar

    我什至附上了一个沙盒链接供你玩

    Live Demo

    【讨论】:

      【解决方案3】:

      如果类型是可变字符串并且它的长度总是13那么:

      $number = '1234567891234';    
      $numberWithSpace = substr($number, -4);
      for ($i = 4; $i < 13; $i+=3) {
          $numberWithSpace = substr($number, -$i, 3) . " " . $numberWithSpace;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-28
        • 2016-03-26
        • 2021-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-07
        • 1970-01-01
        相关资源
        最近更新 更多