Pergunta

I am a very beginner in php. I want to extract the first name and the last name from the full name. The following was my code :-

<?php
$str= "fname lname";
$len=strlen($str);
$s="";
for($i=0;i<=$len;$i++)
{
$sub=substr($str,$i,($i+1));
if($sub!=" ")
{
$s=s+$sub;
}
else {break;}
}
echo $s;
?>

The problem with this code is that the loop runs infinitely and a fatal error is caused. Any help will be appreciated.

Foi útil?

Solução

This is a quick and easy way.

$name = 'John Smith';

list($firstName, $lastName) = explode(' ', $name);

echo $firstName;
echo $lastName;

But if you want to take into account middle names etc,

$name = 'John Mark Smith';
$name = explode(' ', $name);

$firstName = $name[0];
$lastName = (isset($name[count($name)-1])) ? $name[count($name)-1] : '';

The second approach would be better, as it will work for 1 name too.

Outras dicas

Example:

<?php
    $fullname = 'Carlos Fernandes Paddington da Costa Silva';
    $fullname = trim($fullname); // remove double space
    $firstname = substr($fullname, 0, strpos($fullname, ' '));
    $lastname = substr($fullname, strpos($fullname, ' '), strlen($fullname));
?>

Some other answers here will result in undefined errors under some circumstances. I'd do:

$names = explode(' ', $fullname, 2 );
$fname = array_shift( $names );
$lname = array_shift( $names ) or $lname = '';
function Split_Name($name) {
//Pass the Full Name to the function

//Trim the Full Name for any paddings
$name = trim($name);

//Split the Full Name by Spaces
$split_name = explode(' ',$name);

//Then iterate through each Name to get the length  
foreach($split_name as $v) {
   $string []= strlen($v);
}

//Get First Name
$first_name = $split_name[0];
//Get Last Name
$last_name = $split_name[count($string)-1];

//Return the Array of Name Example (1)
//return print_r(array($first_name, $last_name));

//Return As Associative Array Example (2)
return print_r(array('FirstName' => $first_name, 'LastName' => $last_name));}

Split_Name('John Adam McMaster');//Example (1) Output Array ( [0] => John [1] => McMaster )

Split_Name('John Adam McMaster');//Example (2) Output Array ( [FirstName] => John [LastName] => McMaster )

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top