在从右到左的两个字符空格后添加字符


Add character after two character spaces from right to left

我有时间存储在我的数据库中。下面是一个时间的例子:

8001000

第一个是8:00,第二个是10:00。我想在第二个开始从右向左计数的字符后添加一个分号:。如何在php中做到这一点?

这是我尝试的:

$realTime = substr_replace($oldtime,":", 2, -strlen($oldtime));

但是它从左边开始但是我需要它从右边开始计数。谢谢。

Per the docs:

如果start为负值,则替换将从start距字符串末尾第1个字符处开始。

所以使用负数:

$realTime = substr_replace($oldtime,":", -2, -strlen($oldtime));

使用正则表达式

$newtime = preg_replace('#^(.*)([0-9]{2})$#','$1:$2',$oldtime);

另一种方法是根据长度使用不同的公式,并使用case语句。

Update foo 
   set oldtime= case when length(oldtime) = 4 then  
                     concat(substr(oldtime,1,2),':',substr(oldtime,3,2))
                     when length(oldtime) = 3 then 
                     concat(substr(oldtime,1,1),':',substr(oldtime,2,2)) 
                end
工作小提琴