Php – split at the first space in a string

PHPsplit

I have a string like this:

red yellow blue

and I want to get an array like this :

Array (
[0] => red
[1] => yellow blue )

how to split at the first space in a string ?
my code doesn't work

<?php
$str = "red yellow blue";
$preg = preg_split("/^\s+/", $str);
print_r($preg);
?>

please help me.

Best Answer

Use explode with a limit:

$array = explode(' ', $string, 2);

Just a side note: the 3rd argument of preg_split is the same as the one for explode, so you could write your code like this as well:

$array = preg_split('#\s+#', $string, 2);

References:

PHP: explode

PHP: preg_split