43

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.

6 Answers 6

113

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

1
  • 6
    For the curious, the third parameter is the max number of elements in the array, and the last element will take everything left over.
    – Andrew
    Jan 25, 2017 at 19:32
13
<?php
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>

just explode it

5

You can use explode function like this

print_r(explode(' ', $str, 2));

It will set a limit. Check more about it here

3

You can use explode, but if you aren't 100% sure you'll have the same # of spaces (explosions) every time, you can use ltrim to remove the first word and space

<?php
$full='John Doe Jr.';
$full1=explode(' ', $full);
$first=$full1[0];
$rest=ltrim($full, $first.' ');
echo "$first + $rest";
?>
-2

function splitName($name) { $parts = explode(' ', $name); return array( 'firstname' => array_shift($parts), 'lastname' => join(' ', $parts) ); }

-6

You can use explode this way:

  $stringText  = "red yellow blue";
  $colours = explode(" ", $stringText);
  echo $colours[0]; //red 
  echo $colours[1]; //yellow
  echo $colours[2]; //blue

You can also get all the elements of $colours by foreach Loop, but in this case explode is better

1
  • 2
    This would split the string at every space - the question asks for a split at the first space only.
    – Frits
    May 12, 2016 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.