我有一个字符串,我想修改所有 4 位数字并在它们之间插入冒号。示例:1320 将变为 13:20
$data = "The time is 1020 and the time is 1340 and 1550";
我正在考虑使用 preg_match('/[0-9]{4}/', '????', $data);
但不确定如何在 preg 中再次传递相同的值?
最佳答案
一种方法是使用 preg_replace相反,使用捕获组在单词边界 \b
(\d{2})(\d{2})
在替换中使用 2 个捕获组使用 $1:$2
$data = "The time is 1020 and the time is 1340 and 1550";
$data = preg_replace('/\b(\d{2})(\d{2})\b/', "$1:$2", $data);
echo $data;
结果:
The time is 10:20 and the time is 13:40 and 15:50
关于php - 修改字符串内的 4 位数字并插入冒号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549001/