2013-10-18 79 views
10

可能有一個簡單的解決方案,這將導致facepalm。我有時間存儲爲4個字符的長字符串,即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個字符長。

回答

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

編輯:

下面是對這個問題的通用解決方案:

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

Emmm第一個選項返回1:00 .. – Max

+0

第二個返回「50:0」,如果$ time =「500」; – Max

+0

必須從 – Max

6
implode(":",str_split($time,2)); 
1
substr_replace($yourVar, ':', -2, 0); 

將使945結果9:45和1245在12:45。

相關問題