w3resource

PHP String Exercises: Split a string


2. Split String Into Time Format

Write a PHP script to split the following string.

Sample string : '082307'

Visual Presentation:

PHP String Exercises: Split a string

Sample Solution:

PHP Code:

<?php
// Original string
$str1= '082307'; 
// Chunk the string into parts of 2 characters each and insert ':' between them
echo substr(chunk_split($str1, 2, ':'), 0, -1)."\n";
?>

Output:

08:23:07

Explanation:

In the exercise above,

  • $str1= '082307';: Assigns the string '082307' to the variable '$str1'.
  • chunk_split($str1, 2, ':'): Splits the string into chunks of 2 characters each and inserts a ':' between each chunk.
  • substr(..., 0, -1): Removes the last ':' from the resulting string.
  • echo ...: Prints the formatted string.

Flowchart :

Flowchart: Split a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to insert colon separators into a numeric string of fixed length to resemble a time format.
  • Write a PHP function to format a string of 6 digits into HH:MM:SS format, handling cases with invalid length.
  • Write a PHP program to split a numerical string into groups of two using substr() and join them with a colon.
  • Write a PHP script to validate a six-digit string and then output it in a time format while verifying correct segmentation.

Go to:


PREV : Transform String Case Conversions.
NEXT : Check if String Contains Another

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.