explode() 的高级用法

Advanced usage of explode()

我希望用户在单个字段中输入他们的全名,以尝试创建一个流畅的用户体验。

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

我想分解字符串并将部分分配给变量

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

问题 A - 你如何在不知道会有多少爆炸 'pieces' 的情况下瞄准最后一次爆炸?

问题 B - 有没有一种方法可以定位第一个和最后一个之间的所有部分,然后将它们重新组合成一个字符串并添加空格?

一个。你可以使用 end()

end() 将数组的内部指针推进到最后一个元素,returns 它的值。

乙。你可以做类似

的事情
foreach ($exploded as $key=>$value) {
   if ($key == 0 || $key == (count($exploded) -1)) continue;
   $middle_name_array[] = $value;
}

$middle_name = implode(' ', $middle_name_array);

问题 B 可能有更好的解决方案。

$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

评论中解释的工作示例:

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

// Gets first element in $user
$first_name = array_shift($user);

// Gets last element in $user (A)
$last_name = array_pop($user);

// Assign remaining names (B)
$middle_names = implode(" ", $user); // Or just assign $users array (It will only contain those middle names at this point)

问题一:

您可以使用 $last_name = end($user) 定位数组中的最后一项 end() 函数告诉 php 获取数组中的最后一项。

问题 B:

您可以在php中使用array_slice()功能。

array_slice(array,start,length,preserve)

length: Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.

preserve: Optional. Specifies if the function should preserve or reset keys.

所以在你的例子中它会是

$middle_names = implode(" ", array_slice($user,1,-1))

W3Schools array_slice()