Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在字符串中间添加字符_Php_String_Wordpress_Advanced Custom Fields - Fatal编程技术网

Php 在字符串中间添加字符

Php 在字符串中间添加字符,php,string,wordpress,advanced-custom-fields,Php,String,Wordpress,Advanced Custom Fields,可能有一个简单的解决方案,这将导致一个脸掌。我将时间存储为4个字符长的字符串ie 1300 我试图将该字符串显示为13:00。我觉得必须有一个比我现在所做的更优雅的解决方案 我目前有: $startTime = get_field($dayStart, $post->ID); $endTime = get_field($dayEnd, $post->ID); for ($x=0; $x = 4; $x++){ if(x == 2){

可能有一个简单的解决方案,这将导致一个脸掌。我将时间存储为4个字符长的字符串ie 1300

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

我目前有:

$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;
字符串的长度始终为4个字符

$time = "1300";    
$time = substr($time,0,2).':'.substr($time,2,2);
编辑:

以下是此问题的一般解决方案:

function insertAtPosition($string, $insert, $position) {
    return implode($insert, str_split($string, $position));
}

我赞成这个解决方案,因为它只是一个函数

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


将945的结果设为9:45,1245的结果设为12:45。

如果$time=“500”,则第二个返回“50:0”;必须从最后考虑of@Ethan好的音调是一个普遍的解决方案。但您处理了以下任务:)对于您在编辑中编写的自定义函数,有一个本机php函数,请参见下面的答案。当位置为零时,您的通用解决方案会发生什么变化?或者当字符串的长度比位置大数倍时?…:)
substr_replace('1300', ':', 2, 0);
substr_replace( $yourVar, ':', -2, 0 );