2014-09-03 102 views
0

如何將包含姓名和有時中間名的字符串轉換爲具有此格式的數組?將字符串轉換爲特定格式的數組

customFunction('Chris Morris'); 
    // array('firstname' => 'Chris',  'lastname' => 'Morris') 
customFunction('Chris D. Morris'); 
    // array('firstname' => 'Chris D.', 'lastname' => 'Morris') 
customFunction('Chris'); 
    // array('firstname' => 'Chris', 'lastname' => '') 

回答

2

試試這個

function splitName($name){ 
    $name = explode(" ",$name); 
    $lastname= count($name)>1 ? array_pop($name):""; 
return array("firstname"=>implode(" ",$name), "lastname"=>$lastname); 

} 
0
function parseName($input) { 

    $retval = array(); 
    $retval['firstname'] = ''; 
    $retval['lastname'] = ''; 

    $words = explode(' ', $input); 
    if (count($words) == 1) { 
     $retval['firstname'] = $words[0]; 
    } elseif (count($words) > 1) { 
     $retval['lastname'] = array_pop($words); 
     $retval['firstname'] = implode(' ', $words); 
    } 

    return $retval; 
} 
+0

將字符串傳遞給函數時,我得到數組進行字符串轉換。 – MagentoMan 2014-09-03 15:32:27

+0

只是修正了它...雖然我看到兩個其他解決方案更短。我會用其中之一。 – 2014-09-03 15:35:22

1

你可以試試這個:

<?php 
    $arr = 'Chris D. Morris'; 
    function customFunction($str){ 
    $str = trim($str); 
    $lastSpace = strrpos($str," "); 
    if($lastSpace == 0){ 
     $first = $str; 
     return array('firstname' => $first, 'lastname' => $last); 
    }else{ 
    $first = substr($str, 0, $lastSpace); 
    $last = substr($str,$lastSpace); 
    return array('firstname' => $first, 'lastname' => $last); 
    } 
} 
    $got = customFunction($arr); 
    print_r($got); 
    ?> 

希望它幫助。

相關問題