【问题标题】:Add spaces into string dynamically in PHP在 PHP 中动态地将空格添加到字符串中
【发布时间】:2013-06-16 19:10:01
【问题描述】:

我想在每三个数字后面加上一个“-”。
例如:

$number = 123456789;

我想改成123-456-789;

有人可以帮我吗?
谢谢。

【问题讨论】:

  • 尝试将preg_replace 替换为/\d{3}/ 并替换为'$0-'

标签: php arrays dynamic substring


【解决方案1】:

你可以使用chunk_split():

$number = "123456789";
$phone = chunk_split($number,3,"-");
$phone = substr($phone, 0, -1);  // remove trailing hyphen

【讨论】:

    【解决方案2】:

    将字符串拆分为数组并使用 str_split 将其粘回去

    $string = "12345678645465665646346";
     $arr = str_split($string, 3);
     $output = implode("-", $arr);
    echo $output;
    

    【讨论】:

      【解决方案3】:

      这将满足你的愿望:)

      echo trim(chunk_split('123456789', 3, '-'),'-');
      

      【讨论】:

      • 这将留下一个必须去掉的尾随连字符。
      【解决方案4】:

      使用带有以下内容的自动换行:

      $orig = "123456789";
      $str = wordwrap($orig, 3, "-\n" , true);
      echo $str;    
      

      【讨论】:

      • 嗯...我不认为 OP 在每次拆分后都想要一个新行。
      【解决方案5】:

      看看这个解决方案在“-”之后也没有换行

      $output = wordwrap($inputstring, 3, "-&nbsp" , true);
      echo $output;
      

      【讨论】:

        猜你喜欢
        • 2015-10-21
        • 2023-02-04
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 2020-09-16
        • 2012-10-20
        相关资源
        最近更新 更多