Help exploding string right to left with PHP?

I have a name that I would like to explode so I can get two results ... first and last name. The problem is the contact name may include a middle name. I can explode the contact name, as seen below, but rather than isolating a first name and combining the middle with the last, I would prefer to isolate the last name and combine the middle with the first. Is this possible?

For example,
Contact Name = John Jay Doe
[0] = John Jay
[1] = Doe
$fieldName = explode(" ",$fields['contact_name'],2);

Open in new window

Who is Participating?

$conact_name="john smith pelt cans";
$result = preg_match("/(.*) (.*)$/",$conact_name,$matches);


Open in new window

the above will always pick the last name and does not matter how parts the name is made of
$matches[0]=full string
$matches[1]=everything except the last word
$matches[2]=the last word only
Guy Hengel [angelIII / a3]Billing EngineerCommented:
after your explode, when you find 3 (or more) items, you can combine the first and the second into the first, and then unset the second item:
$fieldName = explode(" ",$fields['contact_name'],2);
if (count($fieldName)>=2)
  $fieldName[0] .= $fieldName[1];

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.