PHP String Exercises: Split a string
Write a PHP script to split the following string.
Sample string : '082307'
Visual Presentation:
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 :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to transform a string all cases of letters or words
Next: Write a PHP script to check if a string contains a specific string?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics