在字符串中间添加一个字符 [英] Adding a character in the middle of a string
本文介绍了在字符串中间添加一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对此可能有一个简单的解决方案,它将导致脸红。我将时间存储为4个字符长的字符串,即1300。
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.
我正在尝试将该字符串显示为13:00。我觉得必须要有一个解决方案,它比我现在做的还要优雅。
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.
我目前有:
$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个字符。
The string will always be 4 characters long.
推荐答案
$time = "1300";
$time = substr($time,0,2).':'.substr($time,2,2);
编辑:
以下是此问题的一般解决方案:
Here is a general solution to this problem:
function insertAtPosition($string, $insert, $position) {
return implode($insert, str_split($string, $position));
}
这篇关于在字符串中间添加一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文