Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

The Explode Function, Split a String by String

By Darren W. Hedlund
2005-03-16


PHP Explode Function

explode -- Split a string by string
array explode ( string separator, string string [, int limit])

http://www.developertutorials.com/php-manual/function.explode.html

Ok, so from the prototype above, we can see the function explode() (a function is denoted by the () after the name as this is where you put any parameters) will create an array (oh the joy):

( string separator, string string [, int limit])

The first parameter you must specify is where you want to split up the string from. This is called the separator and must be a string, i.e not an integer or any other type.

( string separator, string string [, int limit])

This is the text that will be exploded. This is called the string and must be of type string, so as above, not any other type.

( string separator, string string [, int limit])

Finally, this limit is optional, denoted by the [squared brackets]. The limit, if you specify it, will explode the string up a set number of times. So if you have a string with 5 words in it all split up by the space, and you specify 2 as the limit, it will only split up the first 2 it encounters.

Note: You must specify the separator and the string in the same order they appear in the prototype otherwise the function will misbehave

So lets explode some stuff....

<?php
// Defining a variable containing some names of my friends (in no particular order)
$friends = 'david matt kieran jon nick andy richard';

// Lets explode this at the space saving the result (an array) as $exploded_friends
$exploded_friends = explode(' ', $friends);
?>


Now the exploded data is stored in the array called $exploded_friends. But we can't just echo that - you have to reference the contents by using a key. So, each of the 7 friends will be in the array numbered from 0 > 6.

So, if I want to echo the name kieran, I would do this after the code above:

<?php
// kieran is number 2 in the array
echo $exploded_friends[2];
?>


Now just to use an example with the limit parameter specified:

<?php
// Defining a variable containing some names of my friends (in no particular order)
$friends = 'david matt kieran jon nick andy richard';

// Lets explode 3 friends at the space saving the result (an array) as $exploded_friends
$exploded_friends = explode(' ', $friends, 3);

// This time display the entire array
echo '<pre>'; // This is just to make it look nice
print_r($exploded_friends);
echo '</pre>';
?>


Tutorial Pages:
» PHP Explode Function


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1