Splitting a string/text at a delimiter is very common use case in php. One can either use php explode (split on a fixed delimiter) or preg_split (split on regex delimiter). Using explode is generally good enough for most use cases. Also note that php function split is now deprecated from PHP 5.3. So we’ll not cover that in this tutorial. Here are some examples using explode and preg_split.
PHP explode on space with no limit
This example splits a string on single space. In case there are two spaces, one empty element will also be present in returned array.
<?php $s="hello world. hello word.\n2ndline"; $arr = explode(" ", $s); print_r($arr); ?>
Array ( [0] => hello [1] => world. [2] => hello [3] => [4] => word. 2ndline )
PHP explode on space with limit 2
Here split is done on first space and rest of the string gets captured in 2nd element. In case there is no space, only one element array is returned.
<?php $s="hello world. hello word.\n2ndline"; $arr = explode(" ", $s, 2); print_r($arr); ?>
Array ( [0] => hello [1] => world. hello word. 2ndline )
PHP preg_split on any whitespace sequence
Using preg_split gives us flexibility to split on a regex. Here is an example where we split on any size whitespace string.
<?php $s="hello world. hello word.\n2ndline"; $arr = preg_split('/\s+/', $s); print_r($arr); ?>
Array ( [0] => hello [1] => world. [2] => hello [3] => word. [4] => 2ndline )
Note that we had two whitespace here. preg_split regex took care of that. Newline is also treated as whitespace.