0

我是php的初学者。我想从全名中提取名字和姓氏。以下是我的代码:-

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

此代码的问题是循环无限运行并导致致命错误。任何帮助将不胜感激。

4

4 回答 4

6

这是一种快速简便的方法。

$name = 'John Smith';

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

echo $firstName;
echo $lastName;

但是如果你想考虑中间名等,

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

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

第二种方法会更好,因为它也适用于 1 个名称。

于 2013-06-22T13:24:19.630 回答
3

例子:

<?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));
?>
于 2015-04-06T14:02:54.960 回答
-1

在某些情况下,这里的一些其他答案会导致未定义的错误。我会做:

$names = explode(' ', $fullname, 2 );
$fname = array_shift( $names );
$lname = array_shift( $names ) or $lname = '';
于 2013-06-22T13:28:29.923 回答
-1
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');//示例(1)输出数组([0] => John [1] => McMaster)

Split_Name('John Adam McMaster');//示例(2)输出数组([FirstName] => John [LastName] => McMaster)

于 2020-06-13T13:39:51.433 回答