How to Split a String into Array by Delimeter in PHP

To split a string into an array by a specific delimiter in PHP, use the explode() function. It will return an array of strings separated by the character(s) specified in the function.

 

Split a PHP String by Each Space Character

A common requirement is to split a string of words into an array by each space character. This can be done using the PHP explode() function by passing a space as the first argument (the delimiter), the string to split as the second and storing the result in a variable.

 

$str = 'This is some text.';

$result = explode(' ', $str);

var_export($result);
array ( 0 => 'This', 1 => 'is', 2 => 'some', 3 => 'text.', )

 

As we can see in the example above, the delimiter characters are automatically removed from the output so there is no need to worry about removing the later.

 

Split Every Character in a PHP String

To split every character in a string use the PHP str_split() function as explode() does not accept an empty delimiter and will throw an error.

 

$str = 'This is some text.';

$result = str_split($str);

var_export($result);
array ( 0 => 'T', 1 => 'h', 2 => 'i', 3 => 's', 4 => ' ', 5 => 'i', 6 => 's', 7 => ' ', 8 => 's', 9 => 'o', 10 => 'm', 11 => 'e', 12 => ' ', 13 => 't', 14 => 'e', 15 => 'x', 16 => 't', 17 => '.', )

 

Limit the Number of Splits to Make

explode() accepts a third argument to limit the number of splits that are made to a string. Let's try this out and observe how it behaves.

 

$str = 'This is some text.';

$result = explode(' ', $str, 2);

var_export($result);
array ( 0 => 'This', 1 => 'is some text.', )

 

As we can see in the above example, explode() lumps the rest of the original string into the last array element if the maximum allowed splits does not meet the required number for the specified delimiter.

 

Conclusion

If you want to split every character in a string use str_split(), for delimiters use explode().

string array