Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get remaining split string on PHP after explode

I want to be able to get the remaining string after an explode.

$string = "First Middle Last";
$d = explode(" ", $string);
print_r($d);

Outputs:
$d = array
(
  [0] => First
  [1] => Middle
  [2] => Last
)

$first = $d[0]; // First
$last = $d[1] // Middle

How can I get the last and remaining exploded values?

I want to be able to do:

$last = $d[last?] // Middle Last

I do not want to do

$last = $d[1].$d[2] // Middle Last
like image 525
Louie Miranda Avatar asked Nov 23 '25 19:11

Louie Miranda


1 Answers

You should probably use the third (optional) argument of explode:

list ($first, $last) = explode(" ", $string, 2);

That said, splitting on spaces is going to work on a lot of human names, but will also fail for quite significant percentage if you take the global view. There's nothing wrong with doing it as a practical solution to a particular problem, just don't expect that it will always work correctly.

like image 134
Jon Avatar answered Nov 26 '25 11:11

Jon