Adding a character in the middle of a string

2019-04-20 19:14发布

There's probably a simple solution to this that will cause a facepalm. I have time stored as a 4 character long string ie 1300.

I'm trying to display that string as 13:00. I feel like there has to be a solution to this that is more elegant than what I'm doing at the moment.

I currently have:

$startTime = get_field($dayStart, $post->ID);
$endTime = get_field($dayEnd, $post->ID);

        for ($x=0; $x = 4; $x++){

            if(x == 2){
                $ST .= ':';
                $ET .= ':';
            } else {
                $ST .= $startTime[x];
                $ET .= $endTime[x];
            }

        }

$startTime = $ST;
$endTime = $ET;

The string will always be 4 characters long.

4条回答
在下西门庆
2楼-- · 2019-04-20 19:41
implode(":",str_split($time,2));
查看更多
Melony?
3楼-- · 2019-04-20 19:43
$time = "1300";    
$time = substr($time,0,2).':'.substr($time,2,2);

Edit:

Here is a general solution to this problem:

function insertAtPosition($string, $insert, $position) {
    return implode($insert, str_split($string, $position));
}
查看更多
何必那么认真
4楼-- · 2019-04-20 19:47
substr_replace( $yourVar, ':', -2, 0 );

Will make 945 result in 9:45 and 1245 in 12:45.

查看更多
女痞
5楼-- · 2019-04-20 19:48

I favor this solution as it is just one function

substr_replace('1300', ':', 2, 0);

http://php.net/substr_replace

查看更多
登录 后发表回答