phpexplode

Split a string on the first and last spaces only


I want a user to enter their full name in a single field in an attempt to create a sleek UX.

$user = 'Robert John Alex Ridly';
$user = explode(' ', $user);

I want explode the string and allocate sections to variables

$first_name = $user[0];
$middle_names = ?
$last_names = $user[last]?;

Problem A - How do you target the last explode without knowing how many exploded 'pieces' there will be?

Problem B - Is there a way to target all pieces between the first and last and put them back together in a string adding the spaces back?


Solution

  • $user = explode(" ", $user); // create the array
    $first_name = array_shift($user); // gets first element
    $last_names = array_pop($user); // gets last element
    $middle_names = implode(" ", $user); // re-unites the rest