Splitting a string with explode()

Splitting a string with explode()Splitting a string into shorter strings couldn’t be easier in PHP. Although there is a PHP function to do this – split(‘delimiter‘, $string), this method is now deprecated and not recommended. A better method would be to use the explode() function.

Make it explode()!

<?php
$my_string = "Joe John Bloggs";
$my_array = explode(" ", $my_string); // Explode string into array. Delimit via spaces.

// Now to retrieve our segments
echo "Your first name is ".$my_array[0].", your middle name is ".$my_array[1]." and your surname ".$my_array[3]."

// You can also limit the amount of splits
$my_address = "Name, Address, City, Postcode, Country";
$my_address_array = explode(" , ", $my_address, 2); // Limit by array[2].

// This would give you an array like this:
/*
Array
(
 [0] => Name
 [1] => Address
 [2] => City, Postcode, Country
)
*/
?>

Leave a Reply

Your email address will not be published. Required fields are marked *