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

Add character after two character spaces from right to left

我的数据库中存储了时间。这是一个时间的例子:

8001000

第一个是8:00,第二个是10:00。我想在从右到左开始计数的第二个字符后添加一个分号:。我如何在 php 中执行此操作?

这是我尝试过的:

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

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

根据 docs:

If start is negative, the replacing will begin at the start'th character from the end of string.

所以使用负数:

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

使用正则表达式

$newtime = preg_replace('#^(.*)([0-9]{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

Working Fiddle