SeniorDeveloper
SeniorDeveloper

Reputation: 906

Convert string into an array with certain format

How can you convert a string that contains your first and last name and sometimes middle name into an array with this format?

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

Upvotes: 0

Views: 82

Answers (3)

Suchit kumar
Suchit kumar

Reputation: 11859

you can try this:

 <?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);
    ?>

hope it helps.

Upvotes: 1

Peter M.
Peter M.

Reputation: 1269

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

Upvotes: 0

Sunand
Sunand

Reputation: 723

Try this

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

}

Upvotes: 2

Related Questions