Everything PHP: Explode and Split

Published on Apr 22, 2009   //  Development

Everything PHP

When processing and sorting data in PHP, you may occasionally need to split a string at a certain point. For example, if you’re retrieving data from a third-party source which is in a non-structured manner, you’ll need to split the data at certain points to get the data you’re actually after.

Depending on the complexity of how you need to spilt up a string, there are two functions to accomplish this. explode() and split().

explode() allows us to take a string, and split it at the point of another string. It will then output a numerical array, with the first value being the data that was before the splitting string and the second value being the data after the splitting string. If the splitting string occurs more than once in the string, subsequent values in the array will have the afterpart in it.

split() is very similar to explode(). The difference is, the point the string is split at can be a regular expression, which allows for more complex splitting. Otherwise it is the same as explode() in regards to the output and syntax. If you want to use Perl-compatible regular expressions, use preg_split().

Let’s take a look at the syntax of explode() (split() takes the same parameters).

[code='php']explode( $splitter , $string [, $limit] );[/code]

  • $splitter – The string (or regular expression, for the split() function) of where you want the $string to be split.
  • $string – The string that you want to be split at $splitter.
  • $limit – (optional) The maximum number of values in the array (the last value will contain the rest of the string. The default is no limit.

Let’s take a look at an example. In this example, we’ll split a string by the string |.

[code='php']$string = 'one|two|three|four';
$explode = explode('|', $string);
print_r($explode);[/code]

Which would give us this result:

Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)

If we were to add a limit parameter, let’s say 3, to this code, we would get:

Array
(
[0] => one
[1] => two
[2] => three|four
)

By using these functions, you can make quick work of processing raw, non-structured data.

4 Comments to “Everything PHP: Explode and Split”

  • Nice article but do provide some coded examples for better understanding. :)

  • Added an example to the post. Sorry about that, must have slipped my mind while I was writing this post.

  • One example for split too! :D

  • split() is identical to explode(), except that the first parameter can be a regular expression. If you want an example, see the documentation for split() or preg_split().

    We’ve yet to cover regular expressions in this series, so giving an example would prompt explaining the regular expression, which would be too indepth for this post.