开发者

PHP: Separate one field in two

As many recommend me to separate firstname and las开发者_高级运维tname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.


It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)

If you just need a quick fix for a legacy database, it might be OK to split by the first space.


Assuming first name always comes first and there's no middle name:

list($firstname, $lastname) = explode(' ', $full_name);

This simply explodes $full_name into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.


You can do:

list($first_name,$last_name) = explode(' ',$full_name);

This assumes that you full name contains first name and last name separated by single space.

EDIT:

In case the lastname is not present, the above method give a warning of undefined offset. To overcome this you can use the alternative method of:

if(preg_match('/^(\S*)\s*(\S*)$/',$full_name,$m)) {
        $first_name = $m[1];
        $last_name = $m[2];
}


$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$lastname = $a[1];


you would need to explode the value into its parts using a space as the separator

http://php.net/manual/en/function.explode.php


I am no PHP programmer, but for a quick fix, without data loss,

$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$count = 1;
$lastname = "";
do {
    $lastname .= $a[$count]." ";
    $count++;
} while($count<count($a));
$lastname = trim($lastname);

This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.


This is the code/solution

    $full_name = "Dude Jackson";
    $a = explode($full_name, " ",1);
    if(count($a) == 2)
    {
       $firstname = $a[0];
       $lastname = $a[1];
    }
    if(count($a) < 2)
    {
       $firstname =  $full_name;
       $lastname  = " ";
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜