如何在多个位置使用substr_replace?
问题描述:
我有一个电话号码,我想在字符串中添加2个空格,我使用substr_replace多次实现此目的。这是可能的一个用途。如何在多个位置使用substr_replace?
$telephone = "07974621779";
$telephone1 = substr_replace($telephone, " ", 3, 0);
$telephone2 = substr_replace($telephone1, " ", 8, 0);
echo $telephone2; //outputs 079 7462 1779
答
所有的这些都将做的工作:
$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
答
可悲的是,你不能只是输入数组作为起始点和终止点是这样的:
$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);
Warni ng:写在浏览器中,完全未经测试,但我认为你明白了。
一人做的伎俩,欢呼 – Sai