php Laravel 5.2 拆分字符串名字姓氏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38268137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.2 Split String First Name Last Name
提问by Dev.Wol
I have a string passed from a form which is full name.
我有一个从全名表单传递的字符串。
in my database I store first name and last name.. I've split the string using the following:
在我的数据库中,我存储了名字和姓氏。我使用以下内容拆分了字符串:
$name = explode(" ", $request->name);
$lastname = array_pop($name);
$firstname = implode(" ", $name);
this works great, however, if the user doesn't enter a surname in the field then the above doesn't work as the lastname becomes the first.
这很好用,但是,如果用户没有在字段中输入姓氏,则上述方法不起作用,因为姓氏成为第一个。
Am I missing something?
我错过了什么吗?
回答by aynber
This is what I've used for splitting names:
这是我用于拆分名称的内容:
$splitName = explode(' ', $name, 2); // Restricts it to only 2 values, for names like Billy Bob Jones
$first_name = $splitName[0];
$last_name = !empty($splitName[1]) ? $splitName[1] : ''; // If last name doesn't exist, make it empty
回答by Conrad Warhol
here's what i like to do:
这是我喜欢做的:
$firstname = explode(' ', trim($fullname))[0];
or with laravel helper head:
或使用 Laravel 助手头:
$firstname = head(explode(' ', trim($fullname)));
or if you are positive that fullname is not empty:
或者如果您确定全名不为空:
$firstname = strtok(trim($fullname), ' ');
回答by rdiz
I usually do this, which is very similar to what you do (using array_shift
instead of array_pop
):
我通常这样做,这与您所做的非常相似(使用array_shift
代替array_pop
):
$split = explode(" ", $request->name);
$firstname = array_shift($split);
$lastname = implode(" ", $split);
Works with both a single name, multiple names and an empty string. No conditionals.
适用于单个名称、多个名称和空字符串。没有条件。
回答by Aleksei Platov
I think it looks not bad :)
我认为它看起来不错:)
list($firstName, $lastName) = array_pad(explode(' ', trim($fullName)), 2, null);