RieqyNS13
RieqyNS13

Reputation: 495

split at the first space in a string

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.

Upvotes: 46

Views: 68729

Answers (6)

seersol
seersol

Reputation: 57

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

Upvotes: -2

Yussuf Maqsood
Yussuf Maqsood

Reputation: 7

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

Upvotes: -6

nvanesch
nvanesch

Reputation: 2600

<?php
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>

just explode it

Upvotes: 16

silkfire
silkfire

Reputation: 25935

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

Upvotes: 117

user2597484
user2597484

Reputation: 41

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";
?>

Upvotes: 4

chandresh_cool
chandresh_cool

Reputation: 11830

You can use explode function like this

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

It will set a limit. Check more about it here

Upvotes: 4

Related Questions