19 11 2007

The explode function in php is very simple to use. The syntax is something like this:

explode( string seperator, string str );

And what the explode() function will do is get the string str as an array and then it will return each “word” separated by the first parameter as it’s own array element.

The example below shows how this works:

$str = “hello this is a string”;
$words = explode(” “, $str);

The explode in this example uses a space as a string separator. The variable $words is assigned to the explode and the print_r echoes out the array $words. The example above will return:

Array ( [0] => hello [1] => this [2] => is [3] => a [4] => string )

You can also use explode() to select specific words, for example, highlight words that have been used in a search query. To this, you basically do the same thing but you use a foreach loop to return each word separately and check it against an if statement.

$sentence = “Hello-this-is-a-sentence”;
$words = explode(“-“, $sentence);

foreach($words as $word){
if($word == $_GET[‘search_term’]){
echo “$word“;
echo “$word “;

That will pretty much check any word that comes from the url which equals “search_term” and highlight it in red if there is a match.

For example, if you have file.php?search_term=Hello-this-is-foo, the separator is the “-” which is set earlier on in the explode and then it will check the string: “Hello-this-is-foo” against the sentence “Hello-this-is-a-sentence” and any words that match will be highlighted.

I hope this has helped your understanding of the explode().

If you have any questions, just comment,

Thanks for reading,





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: