w3resource

PHP String Exercises: Split a string

PHP String: Exercise-2 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-string-exercise-2.php