在php中将文本字符串拆分为$ first和$ last name

时间:2022-05-31 21:40:11

I'm developing a private message system that allows users to search for a user by their full name, e.g.: "George Washington".

我正在开发一个私人消息系统,允许用户以他们的全名搜索用户,例如:“George Washington”。

I have two variables named $firstname and $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"?

我有两个名为$ firstname和$ lastname的变量,搜索功能按相关性排序结果(您向该人发送了多少次消息)。如何获得一个文本字段将“George Washington”拆分为$ firstname =“George”和$ lastname =“Washington”?

10 个解决方案

#1


30  

I like cballou's answer because 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-]*)$#', '$1', $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-]*)$#', '$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;
}

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

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).

它也有假的回报;对于不可识别的名称(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'));

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

#2


86  

The simplest way is, by using explode:

最简单的方法是,使用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);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);

echo "Lastname: $lastname\n";
echo "Firstname: $firstname\n";

Would result:

会导致:

tomatech:~ ariefbayu$ php ~/Documents/temp/test.php 
Lastname: ddd
Firstname: aaa bbb ccc

#3


20  

if you have exactly 2-word input you can use list()

如果你有2个字的输入你可以使用list()

list($firstname, $lastname) = explode(" ", $string);

anyway you can use explode()

无论如何你可以使用explode()

$words = explode(" ", $string);

$firstname = $words[0];
$lastname = $words[1];
$third_word = $words[2];
// ..

#4


13  

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.

第一名:Billy,Last:Johnson,Middle:Bobby。

Of course, if you're seriously wanting some intelligent parsing of names, then something like this (or similar) might be of some use.

当然,如果您真的想要对名称进行一些智能解析,那么像这样(或类似的)可能会有所帮助。

#5


5  

list($firstname, $lastname) = explode(' ', $fullname,2);

#6


3  

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

#7


3  

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_shift()换出array_pop()。

#8


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";

Would result into:

会导致:

first name: Johann Sebastian  
last name: Bach

#9


0  

Code :

代码:

$data='9790,2015-04-04'

$result=explode(','$data);

echo $result[0];

echo $result[1];

Output:

输出:

9790 
2015-04-04

#10


0  

This will ignore the middle and just get the first and last.

这将忽略中间,只是得到第一个和最后一个。

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;
}

#1


30  

I like cballou's answer because 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-]*)$#', '$1', $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-]*)$#', '$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;
}

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

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).

它也有假的回报;对于不可识别的名称(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'));

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

#2


86  

The simplest way is, by using explode:

最简单的方法是,使用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);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);

echo "Lastname: $lastname\n";
echo "Firstname: $firstname\n";

Would result:

会导致:

tomatech:~ ariefbayu$ php ~/Documents/temp/test.php 
Lastname: ddd
Firstname: aaa bbb ccc

#3


20  

if you have exactly 2-word input you can use list()

如果你有2个字的输入你可以使用list()

list($firstname, $lastname) = explode(" ", $string);

anyway you can use explode()

无论如何你可以使用explode()

$words = explode(" ", $string);

$firstname = $words[0];
$lastname = $words[1];
$third_word = $words[2];
// ..

#4


13  

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.

第一名:Billy,Last:Johnson,Middle:Bobby。

Of course, if you're seriously wanting some intelligent parsing of names, then something like this (or similar) might be of some use.

当然,如果您真的想要对名称进行一些智能解析,那么像这样(或类似的)可能会有所帮助。

#5


5  

list($firstname, $lastname) = explode(' ', $fullname,2);

#6


3  

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

#7


3  

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_shift()换出array_pop()。

#8


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";

Would result into:

会导致:

first name: Johann Sebastian  
last name: Bach

#9


0  

Code :

代码:

$data='9790,2015-04-04'

$result=explode(','$data);

echo $result[0];

echo $result[1];

Output:

输出:

9790 
2015-04-04

#10


0  

This will ignore the middle and just get the first and last.

这将忽略中间,只是得到第一个和最后一个。

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;
}