如何在多个位置使用substr_replace?

时间:2017-07-31 11:04:41

标签: php string substring

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

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

echo $telephone2; //outputs 079 7462 1779

2 个答案:

答案 0 :(得分:2)

任何这些都可以完成这项工作:

$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

echo "\n\n";

$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

答案 1 :(得分:0)

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

$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);

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