我正在开发一个私人消息系统,允许用户以他们的全名搜索用户,例如:“George Washington”。
我有两个名为$firstname
和$lastname
的变量,搜索功能按相关性排序结果(您向该人发送了多少次消息)。如何获取文本字段以将“George Washington”分为$firstname="George"
和$lastname="Washington"
?
答案 0 :(得分:94)
最简单的方法是使用explode:
$parts = explode(" ", $name);
获得部件后,将最后一部分弹出$lastname
:
$lastname = array_pop($parts);
最后,将数组的其余部分内容作为$firstname
:
$firstname = implode(" ", $parts);
示例:
$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";
会导致:
tomatech:~ ariefbayu$ php ~/Documents/temp/test.php
Lastname: ddd
Firstname: aaa bbb ccc
答案 1 :(得分:43)
我喜欢cballou's answer,因为我们正在努力检查是否只有名字。我以为我会为其他任何看过的人添加我的功能。
以下是代码:
// 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-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
return array($first_name, $last_name);
}
例1:split_name('Angeler')
输出:
array(
0 => 'Angeler',
1 => ''
);
例2:split_name('Angeler Mcgee')
输出:
array(
0 => 'Angeler',
1 => 'Mcgee'
);
例3:split_name('Angeler Sherlee Mcgee')
输出:
array(
0 => 'Angeler Sherlee',
1 => 'Mcgee'
);
要获得第一个和中间名称分割,
Ex 4:split_name('Angeler Sherlee')
输出:
array(
0 => 'Angeler',
1 => 'Sherlee'
);
后来我决定让中间名自动计算好,如果适用,所以我写了这个函数。
function split_name($name) {
$parts = array();
while ( strlen( trim($name)) > 0 ) {
$name = trim($name);
$string = preg_replace('#.*\s([\w-]*)$#', '$1', $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;
}
例1:split_name('Angeler Sherlee Mcgee')
输出:
array(
'first_name' => 'Angeler',
'middle_name' => 'Sherlee',
'last_name' => 'Mcgee'
);
例2:split_name('Angeler Mcgee')
输出:
array(
'first_name' => 'Angeler',
'middle_name' => '',
'last_name' => 'Mcgee'
);
决定添加另一种不使用正则表达式的方法。
对于不可识别的名称,它也有return false;
(null,空字符串,要推断的词组太多)。
<?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'));
输出
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
答案 2 :(得分:22)
如果你有两个字输入,你可以使用list()
list($firstname, $lastname) = explode(" ", $string);
无论如何,您可以使用explode()
$words = explode(" ", $string);
$firstname = $words[0];
$lastname = $words[1];
$third_word = $words[2];
// ..
答案 3 :(得分:15)
在我的情况下,我只需要一个简单的方法来获得第一个和最后一个,但是考虑到基本的中间名:
$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 . '.';
输出:
第一名:Billy,Last:Johnson,Middle:Bobby。
当然,如果您真的想要对名称进行一些智能解析,那么像this(或类似)这样的东西可能会有所帮助。
答案 4 :(得分:6)
list($firstname, $lastname) = explode(' ', $fullname,2);
答案 5 :(得分:4)
http://php.net/manual/en/function.explode.php
$string = "George Washington";
$name = explode(" ", $string);
echo $name[0]; // George
echo $name[1]; // Washington
答案 6 :(得分:3)
虽然上面的答案是正确的,但它们不提供任何形式的边界条件检查,以确保您实际上有一个有效的名称开头。您可以通过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);
}
值得注意的是,这假设姓氏是一个单词,而名字可以是任何组合。为了产生相反的效果,请为array_pop()
换出array_shift()
。
答案 7 :(得分:3)
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";
会导致:
first name: Johann Sebastian
last name: Bach
答案 8 :(得分:1)
如果您不需要中间名,这是一个简单的解决方案:
$name = "John Doe";
$name = trim($username);
$firstName = strtok($name, " "); // John
$lastName = strtok(" "); // Doe
只有一个名字:
$name = "John";
$name = trim($username);
$firstName = strtok($name, " "); // John
$lastName = strtok(" "); // False
答案 9 :(得分:0)
我还没有看到这个提议:
在我的例子中,我需要将一个名字分成两个字段,first 和 last,不管这个人有多少个名字。所以我做了以下事情:
$fullName = "Paul Thomas Anderson";
$lastname = end(explode(" ", $fullName));
$firstname = str_replace($lastname,'',$fullName);
这导致 $firstname = "Paul Thomas" 和 $lastname = "Anderson"
“end()”命令只是从分解的名称中获取最后一个数组元素,然后“str_replace”从全名中删除姓氏。
答案 10 :(得分:0)
一个行代码可以像
return (explode(" ", $yourName))[0];
答案 11 :(得分:0)
无需太多工作即可获得具有2个元素的数组:
function parse_name($full_name) {
$parts = explode(" ", $full_name);
if (count($parts) > 2) {
$last = array_pop($parts);
return [implode(" ", $parts), $last];
}
return [$parts[0], $parts[1]];
}
Ex 1 parse_name("Johnny Deep");
输出:
array(
0 => "Johnny",
1 => "Deep"
);
Ex 2 parse_name("Lincoln Johnny Deep");
输出:
array(
0 => "Lincoln Johnny",
1 => "Deep"
);
答案 12 :(得分:0)
这是将全名分为姓和名的非常简单的方法
$name = "John Smith";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: John
$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Smith
有姓
$name = "Angeler Sherlee Mcgee";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: Angeler
$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Sherlee Mcgee
答案 13 :(得分:0)
因此,我的用例是根据未经培训的用户输入提取医生的姓名。因此,我编写了此函数来检测最后一个逗号优先的情况以及可能遇到的各种标题和后缀。
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));
}
答案 14 :(得分:0)
我发现这更好地满足了我的需求。它以第一个单词作为名字,其余的则合并为姓氏。
enumerate
答案 15 :(得分:0)
我使用它,它甚至在多个名称都存在的情况下使用&,&和/等拆分名称
function getNames($namestrs){
$allnames= array();
$namestrs = trim($namestrs);
$namestrs = str_replace(array(',',' and ',' & ', '&','/'),'|',$namestrs);
$namestrs = explode('|',$namestrs);
foreach($namestrs as $key=> $namestr){
$namestr = explode(' ',trim($namestr) );
if(count($namestr)==1 || (count($namestr)==2 && strlen(trim($namestr[1]) )<3)){
$firstname = $namestr[0];
if(isset( $namestr[1])){
$middlename = $namestr[1];
}
else{
$middlename ='';
}
$lastname='';
$thenames = $namestrs; //print_r($thenames); //echo $key;
$thenames = array_slice($thenames, $key+1, NULL, TRUE); //print_r($thenames);
foreach($thenames as $c=>$a){
$a = explode(' ',trim($a) );// print_r( $a);
if(count($a)>1 && trim($lastname) ==''){
$lastname = $a[count($a)-1];
}
}
}
else if(count($namestr)==2){
$firstname = $namestr[0];
$middlename = '';
$lastname = $namestr[1];
}
else if(count($namestr)==3){
$firstname = $namestr[0];
$middlename = $namestr[1];
$lastname = $namestr[2];
}
else if(count($namestr)>3){
$firstname = $namestr[0];
$middlename = $namestr[1];
$lastname = str_replace(array( $firstname,$middlename ),"", implode(' ',$namestr));
$lastname = trim($lastname);
}
if($lastname=='3rd') {
$lastname = trim($middlename) ." " .trim($lastname) ;
$middlename ='';
}
$allnames[] = array('firstname'=>$firstname,'middlename'=>$middlename,'lastname'=>$lastname );
}
return $allnames;
}
样本输出Hanna和Mykhoylo Ilyashevych
Array
( [0] =>数组 ( [名字] =>汉娜 [中间名] => [姓氏] =>伊利亚舍维奇 )
[1] => Array
(
[firstname] => Mykhoylo
[middlename] =>
[lastname] => Ilyashevych
)
)
答案 16 :(得分:0)
这将忽略中间,只是得到第一个和最后一个。
function split_name($name) {
$parts = explode(" ", $name);
$lastname = array_pop($parts);
while(count($parts) > 1)
{
array_pop($parts);
}
$firstname = implode(" ", $parts);
$name = array(
'first_name' => $firstname,
'last_name' => $lastname,
);
return $name;
}
答案 17 :(得分:-1)
代码:
$data='9790,2015-04-04'
$result=explode(','$data);
echo $result[0];
echo $result[1];
输出:
9790
2015-04-04