How to split a string by string in PHP?

Posted on

How to split a string by string in PHP? For example,

"a string   separated by space" =>
["a", "string", "separated", "by", "space"]

and

"a,string,separated,by,comma" =>
["a", "string", "separated", "by", "comma"]

The commonly used `explode()` is not enough here because multiple delimiters should be consider as one (such as " ", 3 spaces together, is consider a single delimiter). Instead, the `preg_split()` function can be used to use regular expression to handle such cases.

One example is as follows.

$ php -a
Interactive mode enabled

php > $str = "a string   separated by space";
php > $splits = preg_split('/\s+/', $str);
php > print_r($splits);
Array
(
    [0] => a
    [1] => string
    [2] => separated
    [3] => by
    [4] => space
)
php > 

For another example,

php > $str = "a,string,separated,by,comma";
php > $splits = preg_split('/,+/', $str);
php > print_r($splits);
Array
(
    [0] => a
    [1] => string
    [2] => separated
    [3] => by
    [4] => comma
)

Related Posts