banditKing
banditKing

Reputation: 9579

php string tokenizing

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?

Upvotes: 1

Views: 6426

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270609

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;
}

Upvotes: 4

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

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.

Upvotes: 0

Related Questions