String Explode and Implode

Onto my two favorite string functions in PHP, explode and implode.

PHP Explode

The explode function is awesome because it breaks a string into manageable parts, like words. You can easily create a PHP program using explode and other PHP functions to create a program that performs a word count. I crafted a program like this in college because I have a terrible tendency to use the same words, and apparently professors think that means you have a limited mind. I showed them. Enough bragging, more coding.

Example

Result

Array ( [0] => I [1] => am [2] => a [3] => long [4] => and [5] => redundant [6] => sentence [7] => that [8] => serves [9] => no [10] => purpose [11] => except [12] => to [13] => be [14] => an [15] => example. )

We employ our print_r class to print out our array in a way that is readable. Inside that function, we have our explode function. First, we say that we want to separate everything by spaces, ” “, and we want to break up $myString. We could pass anything we want into the first parameter, and PHP will find any matches and explode the parts around it into an array. However, when you match something using explode, it does not include the matched string. In our example, we matched spaces, but in our array the spaces are completely eliminated. There is a third optional parameter to limit the number of words you want to break up, which you can add on the end. PHP Explode is finished. Let’s be more constructive in the next section.

PHP Implode

Enough of blowing things apart. Let’s start putting them back together with the PHP implode function. The implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array. Ok, we’re sorry. We’ll put it back together.

Example

Result

I am a long and redundant sentence that serves no purpose except to be an example.

Our code is almost identical to the example above, but we are not printing it out until we use our next function implode. In our implode function, we simply say we want to join all of the items in our array $newArray together, but please separate them with a space, ” “. Boom! We blew a string into pieces, and then put it again together like a boss.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. The result for the first example on my test is:
    Array ( [0] => I [1] => am [2] => a [3] => long [4] => and [5] => redundant [6] => sentence [7] => that [8] => serves [9] => no [10] => purpose [11] => except [12] => to [13] => be [14] => an [15] => example. )

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.