将文本字符串拆分为 php 中的 $first 和 $last name
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13637145/
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
Split text string into $first and $last name in php
提问by centree
I'm developing a private message system that allows users to search for a user by their full name, e.g.: "George Washington".
我正在开发一个私人消息系统,允许用户按全名搜索用户,例如:“乔治华盛顿”。
I have two variables named $firstnameand $lastname, and the search function orders results by relevancy (how many times you have messaged that person). How do I get a text field to split "George Washington" into $firstname="George"and $lastname="Washington"?
我有两个名为$firstnameand 的变量$lastname,搜索函数按相关性(您向该人发送消息的次数)对结果进行排序。如何让文本字段将“乔治华盛顿”拆分为$firstname="George"和$lastname="Washington"?
回答by ariefbayu
The simplest way is, by using explode:
最简单的方法是,通过使用爆炸:
$parts = explode(" ", $name);
After you have the parts, pop the last one as $lastname:
拥有零件后,将最后一个弹出为$lastname:
$lastname = array_pop($parts);
Finally, implode back the rest of the array as your $firstname:
最后,将数组的其余部分内爆为您的$firstname:
$firstname = implode(" ", $parts);
example:
例子:
$name = "aaa bbb ccc ddd";
$parts = explode(" ", $name);
if(count($parts) > 1) {
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
}
else
{
$firstname = $name;
$lastname = " ";
}
echo "Lastname: $lastname\n";
echo "Firstname: $firstname\n";
Would result:
会导致:
tomatech:~ ariefbayu$ php ~/Documents/temp/test.php
Lastname: ddd
Firstname: aaa bbb ccc
回答by amurrell
I like cballou's answerbecause there's an effort to check if there's only a first name. I thought I'd add my functions for anyone else who comes lookin'.
我喜欢cballou 的回答,因为要检查是否只有名字。我想我会为任何来找我的人添加我的功能。
Simple Function, Using Regex (word char and hyphens)
简单函数,使用正则表达式(字符和连字符)
- It makes the assumption the last name will be a single word.
- Makes no assumption about middle names, that all just gets grouped into first name.
- You could use it again, on the "first name" result to get the first and middle though.
- 它假设姓氏将是一个单词。
- 不对中间名做任何假设,所有只是被分组到名字中。
- 您可以再次使用它,在“名字”结果上获得第一个和中间的结果。
Here's the code:
这是代码:
// uses regex that accepts any word character or hyphen in last name
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
return array($first_name, $last_name);
}
Ex 1: split_name('Angeler')outputs:
例 1:split_name('Angeler')输出:
array(
0 => 'Angeler',
1 => ''
);
Ex 2: split_name('Angeler Mcgee')outputs:
例 2:split_name('Angeler Mcgee')输出:
array(
0 => 'Angeler',
1 => 'Mcgee'
);
Ex 3: split_name('Angeler Sherlee Mcgee')outputs:
例 3:split_name('Angeler Sherlee Mcgee')输出:
array(
0 => 'Angeler Sherlee',
1 => 'Mcgee'
);
To get the first and middle name split,
要拆分名字和中间名,
Ex 4: split_name('Angeler Sherlee')outputs:
例 4:split_name('Angeler Sherlee')输出:
array(
0 => 'Angeler',
1 => 'Sherlee'
);
Another Function - Detects Middle Names Too
另一个功能 - 也检测中间名
Later I decided that it would be nice to have the middle name figured out automatically, if applicable, so I wrote this function.
后来我决定如果适用的话,自动计算中间名会很好,所以我写了这个函数。
function split_name($name) {
$parts = array();
while ( strlen( trim($name)) > 0 ) {
$name = trim($name);
$string = preg_replace('#.*\s([\w-]*)$#', '', $name);
$parts[] = $string;
$name = trim( preg_replace('#'.$string.'#', '', $name ) );
}
if (empty($parts)) {
return false;
}
$parts = array_reverse($parts);
$name = array();
$name['first_name'] = $parts[0];
$name['middle_name'] = (isset($parts[2])) ? $parts[1] : '';
$name['last_name'] = (isset($parts[2])) ? $parts[2] : ( isset($parts[1]) ? $parts[1] : '');
return $name;
}
Ex 1: split_name('Angeler Sherlee Mcgee')outputs:
例 1:split_name('Angeler Sherlee Mcgee')输出:
array(
'first_name' => 'Angeler',
'middle_name' => 'Sherlee',
'last_name' => 'Mcgee'
);
Ex 2: split_name('Angeler Mcgee')outputs:
例 2:split_name('Angeler Mcgee')输出:
array(
'first_name' => 'Angeler',
'middle_name' => '',
'last_name' => 'Mcgee'
);
Another Way - Sans Regex
另一种方式 - Sans Regex
Decided to add another way that doesn't use regex.
决定添加另一种不使用正则表达式的方式。
It also has return false;for non-recognizable names (null, empty string, too many word groups to infer).
它还具有return false;不可识别的名称(空、空字符串、太多无法推断的词组)。
<?php
function split_name($string) {
$arr = explode(' ', $string);
$num = count($arr);
$first_name = $middle_name = $last_name = null;
if ($num == 2) {
list($first_name, $last_name) = $arr;
} else {
list($first_name, $middle_name, $last_name) = $arr;
}
return (empty($first_name) || $num > 3) ? false : compact(
'first_name', 'middle_name', 'last_name'
);
}
var_dump(split_name('Angela Mcgee'));
var_dump(split_name('Angela Bob Mcgee'));
var_dump(split_name('Angela'));
var_dump(split_name(''));
var_dump(split_name(null));
var_dump(split_name('Too Many Names In Here'));
Outputs
输出
Array
(
[first_name] => Angela
[middle_name] => NULL
[last_name] => Mcgee
)
Array
(
[first_name] => Angela
[middle_name] => Bob
[last_name] => Mcgee
)
Array
(
[first_name] => Angela
[middle_name] => NULL
[last_name] => NULL
)
false
false
false
回答by vlcekmi3
回答by mhulse
In my situation, I just needed a simple way to get first and last, but account for basic middle names:
在我的情况下,我只需要一种简单的方法来获取第一个和最后一个,但要考虑基本的中间名:
$parts = explode(' ', 'Billy Bobby Johnson'); // $meta->post_title
$name_first = array_shift($parts);
$name_last = array_pop($parts);
$name_middle = trim(implode(' ', $parts));
echo 'First: ' . $name_first . ', ';
echo 'Last: ' . $name_last . ', ';
echo 'Middle: ' . $name_middle . '.';
Output:
输出:
First: Billy, Last: Johnson, Middle: Bobby.
第一:比利,最后:约翰逊,中间:鲍比。
回答by Sultan
list($firstname, $lastname) = explode(' ', $fullname,2);
回答by Corey Ballou
Here's an answer with some bounds checking.
这是一个带有一些边界检查的答案。
While the answers above are correct, they don't provide any form of bounds condition checks to ensure you actually have a valid name to begin with. You could go about this with a strpos()check to see if a space exists. Here's a more thorough example:
虽然上面的答案是正确的,但它们不提供任何形式的边界条件检查来确保您实际上有一个有效的名称开始。您可以通过strpos()检查来查看是否存在空间。这是一个更彻底的例子:
function split_name($name)
{
$name = trim($name);
if (strpos($name, ' ') === false) {
// you can return the firstname with no last name
return array('firstname' => $name, 'lastname' => '');
// or you could also throw an exception
throw Exception('Invalid name specified.');
}
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
return array('firstname' => $firstname, 'lastname' => $lastname);
}
It's worth noting that this assumes the lastname is a single word whereas the firstname can be any combination. For the opposite effect, swap out array_pop()for array_shift().
值得注意的是,这假设姓氏是一个单词,而名字可以是任意组合。为相反的效果,换出array_pop()为array_shift()。
回答by Alvarez
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.explode.php
$string = "George Washington";
$name = explode(" ", $string);
echo $name[0]; // George
echo $name[1]; // Washington
回答by Nik Sumeiko
function getFirstName($name) {
return implode(' ', array_slice(explode(' ', $name), 0, -1));
}
function getLastName($name) {
return array_slice(explode(' ', $name), -1)[0];
}
$name = 'Johann Sebastian Bach';
$firstName = getFirstName($name);
$lastName = getLastName($name);
echo "first name: $firstName\n";
echo "last name: $lastName\n";
Would result into:
将导致:
first name: Johann Sebastian
last name: Bach
回答by danielson317
So my use case was to extract the name of a doctor based on an untrained users input. So I wrote this function to detect the last-comma-first scenario and various titles and suffixes that I may encounter.
所以我的用例是根据未经训练的用户输入提取医生的名字。所以我写了这个函数来检测最后一个逗号优先的场景以及我可能遇到的各种标题和后缀。
Assumptions
假设
- It will probably require some fine tuning as this has not been beta tested yet. I will try to remember to update this post as I patch the function.
- The prefix/suffix list will need to be customized for each use case as a comprehensive list would actually be detrimental to functionality. (e.g. A "Mrs. Bishop" or "Dr. Ma" would be empty)
- Also only middle initial is pulled and the middle names beyond the first encountered are ignored.
- 它可能需要一些微调,因为它还没有经过 beta 测试。当我修补该功能时,我会尽量记住更新这篇文章。
- 需要为每个用例自定义前缀/后缀列表,因为一个全面的列表实际上会损害功能。(例如“Mrs. Bishop”或“Dr. Ma”为空)
- 也只提取中间名首字母,忽略第一个遇到的中间名。
Code
代码
function extractName($name)
{
// Common/expected prefixes.
$prefix_list = array(
'mr',
'mrs',
'miss',
'ms',
'dr',
'doctor',
);
// Common/expected suffixes.
$suffix_list = array(
'md',
'phd',
'jr',
'sr',
'III',
);
$parts = explode(' ', $name);
// Grab the first name in the string.
do
{
$first_name = array_shift($parts);
} while ($first_name && in_array(str_replace('.', '', strtolower($first_name)), $prefix_list));
// If the first name ends with a comma it is actually the last name. Adjust.
if (strpos($first_name, ',') === (strlen($first_name) - 1))
{
$last_name = substr($first_name, 0, strlen($first_name) - 1);
$first_name = array_shift($parts);
// Only want the middle initial so grab the next text in the array.
$middle_name = array_shift($parts);
// If the text is a suffix clear the middle name.
if (in_array(str_replace('.', '', strtolower($middle_name)), $suffix_list))
{
$middle_name = '';
}
}
else
{
// Retrieve the last name if not the leading value.
do
{
$last_name = array_pop($parts);
} while ($last_name && in_array(str_replace('.', '', strtolower($last_name)), $suffix_list));
// Only want the middle initial so grab the next text in the array.
$middle_name = array_pop($parts);
}
return array($first_name, $last_name, substr($middle_name, 0, 1));
}
Output
输出
回答by Ajay Patidar
Here is a very simple way to split full name into first name and last name
这是将全名拆分为名字和姓氏的一种非常简单的方法
$name = "John Smith";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: John
$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Smith
With Middle Name
有中间名
$name = "Angeler Sherlee Mcgee";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: Angeler
$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Sherlee Mcgee


