为什么在使用爆炸时打印逗号?

Why are Comma's being printed when using explode?

我有一串名字,我想打印它们。我正在使用 explode 函数。它有效,但是,我的逗号正在打印名称,我不希望这样。我怎样才能让他们不打印?任何帮助表示赞赏。还有如何让我的代码更有效率?

$input = 'Jrew Low, Bill Wilt, Law Naw, Ing Holp';

list($fName, $lName, $fNameTwo, $lNameTwo, $fNameThree, $lNameThree, $fNameFour, $lNameFour) = explode(' ', $formInputNames);
if ($formInputNames == empty($fName) && empty($lName) || empty($fNameTwo) && empty($lNameTwo)){
    echo "No Valid Name";
} else {
// while ($fName == empty($formInputNames)){
//  echo "something is missing";
// }
echo "First Name: $fName <br> Last Name: $lName <br>";
echo "Email Address: $fName$email <br><br>";
echo "First Name: $fNameTwo <br> Last Name: $lNameTwo <br>";
echo "Email Address: $fNameTwo$email <br><br>";
echo "First Name: $fNameThree <br> Last Name: $lNameThree <br>";
echo "Email Address: $fNameThree$email <br><br>";
echo "First Name: $fNameFour <br> Last Name: $lNameFour <br>";
echo "Email Address: $fNameFour$email <br><br>";
}

输出:

First Name: Jrew

Last Name: Low,

First Name: Bill

Last Name: Wilt,

First Name: Law

Last Name: Naw,

First Name: Ing

Last Name: Holp

explode(' ', $formInputNames)改为explode(', ', $formInputNames)

您只是按空格拆分,但您还想按逗号拆分以删除它们。

为什么要打印逗号?因为 explode 空格 上拆分字符串 - 你没有告诉它用逗号做任何事情。

因为你在 explode 函数中的分隔符是 " " (space)。当您将字符串从 space 中拆分出来时,为什么您认为逗号会消失?

先用

拆分
explode(", ", $input);

这将为您提供全名列表。稍后您可以将其拆分一次以分别获得名字和姓氏:

explode(" ", $fullname);

但我个人认为,与其将所有这些名称和姓氏绑定到不同的变量。将它们放入数组中并通过遍历数组打印名称。

$input = 'Jrew Low, Bill Wilt, Law Naw, Ing Holp';
$fullnames = explode(", ", $input);

foreach ($fullnames as $fullname) {
    $nameSplit = explode(" ", $fullname);
    echo 'First Name: ' . $nameSplit[0];
    echo 'Last Name: ' . $nameSplit[1];
}

现在我明白了这个问题..这是最简单的方法..

$input = 'Jrew Low, Bill Wilt, Law Naw, Ing Holp';
$chunks = explode(" ", $input);
foreach($chunks as $index=>$name)
    echo ($index % 2 ? "Last" : "First") . " name: ".trim($name, ", ")."\n";

Here's a fiddle