1

Wondering if I could get some advice on tokenizing a string in php since Im relatively new to the language.

I have this:

$full_name = "John Smith"

I want to use a string function that will extract the first name and last name into indices of an array.

$arr[0] = "John"
$arr[1] = "Smith"

However, the function should also be able to handle the situation:

$full_name = "John Roberts-Smith II"
$arr[0] = "John"
$arr[1] = "Roberts-Smith II"

or

$full_name = "John"
$arr[0] = ""
$arr[1] = "John"

any suggestions on where to begin?

1
  • First you have to think about what constitutes a first name and a last name. Commented Jul 29, 2011 at 13:53

2 Answers 2

4

Use explode() with the optional limit param:

$full_name = "John Roberts-Smith II"

// Explode at most 2 elements
$arr = explode(' ', $full_name, 2);

// Your values:
$arr[0] = "John"
$arr[1] = "Roberts-Smith II"

Your last case is special though, placing the first name into the second array element. That requires special handling:

// If the name contains no whitespace,
// put the whole thing in the second array element.
if (!strpos($full_name, ' ')) {
   $arr[0] = '';
   $arr[1] = $full_name;
}

So a complete function:

function split_name($name) {
  if (!strpos($name, ' ')) {
    $arr = array();
    $arr[0] = '';
    $arr[1] = $name;
  }
  else $arr = explode(' ', $name, 2);

  return $arr;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Michael. I will try this example. Appreciate your help
@user657514 be sure to change the $full_name to $name - I just fixed the typo above.
0

You should explode() function for this purpose.

$name_splitted = explode(" ", "John Smith", 2);
echo $name_splitted[0]; // John
echo $name_splitted[1]; // Smith

From the documentation -

array explode ( string $delimiter , string $string [, int $limit ] )

Returns an array of strings, each of which is a substring of "string" formed by splitting it on boundaries formed by the string "delimiter". If "limit" is set and positive, the returned array will contain a maximum of "limit" elements with the last element containing the rest of string. If the "limit" parameter is negative, all components except the last -"limit" are returned. If the "limit" parameter is zero, then this is treated as 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.