Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a character in the middle of a string

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.

like image 470
Baadier Sydow Avatar asked Oct 18 '13 14:10

Baadier Sydow


People also ask

How do you add a character to the middle of a string in Python?

Use concatenation to insert a character into a string at an index. To insert a character into a string at index i , split the string using the slicing syntax a_string[:i] and a_string[i:] . Between these two portions of the original string, use the concatenation operator + to insert the desired character.

How do you insert a character in a string at a certain position?

One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.

Can you add a character to a string?

Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.


1 Answers

$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));
}
like image 75
Ethan Avatar answered Sep 23 '22 04:09

Ethan