我希望用户在一个字段中输入他们的全名,以尝试创建一个漂亮的UX。
$user = 'Robert John Alex Ridly';
$user = explode(' ', $user);我要爆掉字符串,并将部分分配给变量。
$first_name = $user[0];
$middle_names = ?
$last_names = $user[last]?;问题A-你如何瞄准最后一次爆炸,而不知道会有多少爆炸的“碎片”?
问题B-是否有一种方法可以将第一个和最后一个之间的所有部分对准,并将它们组合在一个字符串中,将空格加回?
发布于 2015-12-20 04:15:05
$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发布于 2015-12-20 04:14:41
你可以使用end()
end()推进数组指向最后一个元素的内部指针,并返回其值。
你可以做这样的事情
foreach ($exploded as $key=>$value) {
if ($key == 0 || $key == (count($exploded) -1)) continue;
$middle_name_array[] = $value;
}
$middle_name = implode(' ', $middle_name_array);问题B可能有更好的解决办法。
发布于 2015-12-20 04:15:20
如注释中所解释的那样,工作示例:
$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)https://stackoverflow.com/questions/34377882
复制相似问题