我是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;
?>
此代码的问题在于循环无限运行并导致致命错误。 任何帮助将不胜感激。
答案 0 :(得分:2)
这是一种快速简便的方法。
$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个名字。
答案 1 :(得分:1)
示例:
<?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));
?>
答案 2 :(得分:-1)
此处的其他一些答案在某些情况下会导致未定义的错误。我会这样做:
$names = explode(' ', $fullname, 2 );
$fname = array_shift( $names );
$lname = array_shift( $names ) or $lname = '';
答案 3 :(得分:-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)