PHP - String Explode/Implode

November 10, 2007

PHP - String Explode

Explode is a PHP function which let as divide a string into smaller pieces. For example, if you need the words from a sentence you can call explode to divide it using the space delimitation. The great part is that the result will be stored in an array.

The first argument that explode takes is the delimiter which is used to divide the second parameter, the original string. The explode function returns an array from string pieces from the original string. Lets have an example with a phone number. The delimitation is made by “-”.

PHP Code

$phoneNumber = "900-555-5555";
$phoneChunks = explode("-", $phoneNumber);
echo "Phone Number = $phoneNumber <br />";

echo "First chunk = $phoneChunks[0]<br />";

echo "Second chunk = $phoneChunks[1]<br />";

echo "Third Chunk chunk = $phoneChunks[2]";

Display

Phone Number = 900-555-5555First chunk = 900

Second chunk =  555

Third Chunk chunk = 5555

We can control the amount of smaller pieces using the third (optional) argument which allows to set the number of pieces. This means it will stop exploding once the number of pieces equals the set limit. The limited explosion has 4 pieces (starting from 0, ending at 3). Below we have an example:

The PHP code

$string = "Some simple example of this function";

$wordChunks = explode(" ", $strings);

for($i = 0; $i < count($wordChunks); $i++){

echo "Piece $i = $wordChunks[$i] <br />";

}

$wordChunksLimited =explode(" ", $string, 4);

for($i = 0; $i < count($ChunksLimited); $i++){echo "Limited Piece $i = $ChunksLimited[$i] <br />";

}

Display

Piece 0 =Some

Piece 1 = simple

Piece 2 = example

Piece 3 = of

Piece 4  = this

Piece 5 = function
Limited Piece 0 = Some

Limited Piece 1 = simple

Limited Piece 2 = example

Limited Piece 3 = of this function

PHP - Array implode

The PHP function implode operates on an array and is known as the “undo” function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string. So see the example below:

$pieces = array("PHP", "array,", "implode");
$TogetherSpaces = implode(" ", $pieces);
$TogetherDashes = implode("-", $pieces);
for($i = 0; $i < count($pieces); $i++){
echo "Piece #$i = $pieces[$i] <br />";
}

echo "Sentence with spaces = $TogetherSpaces <br />";

echo "Sentence with dashes = $TogetherDashes";

Piece #0 = PHP Piece #1 = array Piece #2 = implode Sentence with spaces = PHP array implode Sentence with dashes = PHP-array-implode

 

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word