【问题标题】:How to use substr_replace at multiple positions?如何在多个位置使用 substr_replace?
【发布时间】:2017-07-31 11:04:40
【问题描述】:

我有一个电话号码,我想在字符串中添加 2 个空格,我多次使用 substr_replace 来实现这一点。这是否可能一次使用。

$telephone = "07974621779";
$telephone1 = substr_replace($telephone, " ", 3, 0);
$telephone2 = substr_replace($telephone1, " ", 8, 0);

echo $telephone2; //outputs 079 7462 1779

【问题讨论】:

    标签: php string substring


    【解决方案1】:

    其中任何一个都可以完成这项工作:

    $telephone = "07974621779";
    $telephone=substr_replace(substr_replace($telephone," ",3,0)," ",8,0);
    // sorry still two function calls, but fewer lines and variables
    echo $telephone; //outputs 079 7462 1779
    

    或者

    $telephone="07974621779";
    $telephone=preg_replace('/(?<=^\d{3})(\d{4})/'," $1 ",$telephone);
    // this uses a capture group and is less efficient than the following pattern
    echo $telephone; //outputs 079 7462 1779
    

    或者

    $telephone="07974621779";
    $telephone=preg_replace('/^\d{3}\K\d{4}/',' $0 ',$telephone);
    // \K restarts the fullstring match ($0)
    echo $telephone; //outputs 079 7462 1779
    

    或者

    $telephone = preg_replace('/(?=(?:\d{4}){1,2}$)/', ' ', $telephone);
    

    甚至

    $telephone = implode(' ', sscanf($telephone, '%3s%4s%4s'));
    

    【讨论】:

      【解决方案2】:

      遗憾的是,您不能像这样只输入数组作为开始值和结束值:

      $telephone1 = substr_replace($telephone, " ", array(3, 8), array(0, 0));
      

      这意味着您可能需要编写自己的包装函数:

      function substr_replace_mul($string, $replacement, $start, $end) {
         // probably do some error/sanity checks
         for ($i = 0; $i < count($start); $i++) {
             $string = substr_replace($string, $replacement, $start[$i], is_array($end) ? $end[$i] : $end);
         }
      
         return $string;
      }
      

      用法:

      $telephone1 = substr_replace_mul($telephone, " ", array(3, 8), 0);
      

      警告:写在浏览器中并且完全未经测试,但我想你明白了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 2017-11-20
        • 2012-04-14
        相关资源
        最近更新 更多