Split

The split function lets us break apart strings, using regular expressions to specify the matching strings that will be used as the boundaries for that splitting. A simple usage is just to list a character to use to split apart a string:

$array = split(':', "One:Two:Three');

The preceding code returns an array with three strings in it, namely One, Two, and Three. Regular expressions, however, let us be more flexible:

$array = split('[|:, ]', 'One|Two:Three Four,Five');

The first parameter in the preceding code says to use any of the characters as a valid separator, so we will see an array with five strings in it after executing this code:

Array
(
[0] => One
[1] => Two
[2] => Three
[3] => Four
[4] => Five
)

If we have a very long string that represents a number of lines of text, each separated by a newline character, we can write the following code to split them up:

The $array variable now contains each of the lines in the $exTRemely_long_text variable as individual values within the array (without any of the newline characters).

PHP includes another function that does something similar to split called explode. This function is not multi-byte character safe, but it is significantly faster than split. We will therefore use these functions interchangeably. We will use explode when we are absolutely guaranteed that our input is in single-byte character sets such as ISO-8859-1, and split when we are dealing with user input.