1

If I have a name, "Jane & John Doe" and would like to split the two like so: $first = "Jane & John" and $last = "Doe". How do I do that? I know I should have something like this:

$name = "Jane & John Doe";
$name = explode(" ", $name);
$first = array_shift($name);
$last = array_pop($name);

I know that will only give me "Jane" and "Doe". Can I do the array_pop() first and then convert the rest of the array to a string?

5
  • 1
    Why not try it and see? Commented Nov 7, 2013 at 2:57
  • I don't know how to do that in php. Commented Nov 7, 2013 at 2:58
  • 2
    You'll have to be more specific about the split rule...otherwise in this particular example, you can just do $last=array_pop($name); $first=implode(" ",$name);. Commented Nov 7, 2013 at 2:59
  • Or better yet, read up on regex. Just because clumsy explode and shifting workarounds are commonplace doesn't mean they're the best option here. Commented Nov 7, 2013 at 3:00
  • You can use phpfiddle.org Commented Nov 7, 2013 at 3:00

1 Answer 1

1

Here you go.

You explode the string based on the space character. You then "pop" the last element of the array into $last. The remaining members of the array are then imploded, using the space character as the "glue"

$name = "Jane & John Doe";
$exploded = explode(" ", $name);
$last = array_pop($exploded);
$first = implode(" ", $exploded);
echo $first . " " . $last;

You can learn a whole lot more from php.net. It has a lot of examples to go with it.

This is just a method of doing it. There are other ways of achieving your goal. Just be creative .. :-)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.