php 在字符串中间添加一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19452392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:30:00  来源:igfitidea点击:

Adding a character in the middle of a string

phpstringwordpressadvanced-custom-fields

提问by Baadier Sydow

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.

可能有一个简单的解决方案会导致面部出现问题。我将时间存储为 4 个字符长的字符串,即 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.

我试图将该字符串显示为 13:00。我觉得必须有一个比我目前正在做的更优雅的解决方案。

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 个字符长。

回答by Ethan

$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));
}

回答by Frankey

I favor this solution as it is just one function

我喜欢这个解决方案,因为它只是一个功能

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

http://php.net/substr_replace

http://php.net/substr_replace

回答by SheetJS

implode(":",str_split($time,2));

回答by arjentuin

substr_replace( $yourVar, ':', -2, 0 );

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

将使 945 在 9:45 和 1245 在 12:45 结果。