【发布时间】:2015-03-02 15:23:49
【问题描述】:
我对任何编码都很陌生,所以如果这看起来很基本,请多多包涵。
我正在尝试使用变量 $fname 在电子邮件中分配适当的问候语。名称值源自的数据是一个简单的单个字符串。因此,可能的格式变化是很多的。
在这个特定的应用程序中,细节大多写成:
-约翰·史密斯先生
-史密斯先生
-约翰·史密斯
-约翰
因此,我需要先评估用于输入名称的方法,然后才能将其分配给变量。
我已经编写了以下代码,但是在线检查会抛出“意外的 'else'”。
这一切对我来说似乎都是正确的,我看过的在线示例似乎遵循类似的顺序。
非常感谢任何帮助!
谢谢,
罗伯。
OK - 使用正确的、经过实际测试的工作代码再次编辑。 (我昨天很累,错过了一个可能的结果)这绝对适用于我需要的所有排列。希望它可以为其他初学者节省我做这么简单的事情所花费的疯狂时间!
再次感谢所有为我的“新手”提供帮助和道歉的人。
<?php
$saltest = explode(" ", $client);
if (empty($saltest[1])) { // checks to see if it a single name eg 'John'.
$fname = $saltest[0];
} elseif (isset($saltest[1])) { // if it is not a single word, checks to see if starts with a salutation
switch ($saltest[0]) {
case 'Mr';
case 'Mrs';
case 'Ms';
case 'Mr.';
case 'Mrs.';
case 'Ms.';
case 'Dr';
case 'Dr.';
$withsal = $saltest; // if it does, allocate the array to variable $withsal.
break;
default: $withoutsal = $saltest; // if it doesn't - allocate it to variable $withoutsal.
break;
}
}
if (isset($withoutsal)) { // if already established that there is no salutation, issue the $fname & $lname variables
$fname = $withoutsal[0];
$lname = $withoutsal[1];
} elseif (isset($withsal) and isset($withsal[2])) { // if it has a salutation and is compised of 3 words - issue $fname & $lname accordingly.
$fname = $withsal[1];
$lname = $withsal[2];
} elseif (isset($withsal) and isset($withsal[1])) { // if it has a salutation but is only 2 words, put them together to create variable $fname eg. "Mr Smith" and declare the $lname variable as NULL. It is not needed.
$fname = implode(" ", $withsal);
$lname = NULL;
}
echo $fname;
?>
【问题讨论】:
-
if {...} else {...} else {...},第三块什么时候执行? -
您需要在 else 语句中添加表达式:
elseif(expression)... -
添加右括号,你的else没有关闭。
-
Biffen: If...if...else...else...if...else... 如果第一个 if 是正确的,但不是第二个。
-
@RobKane 不是你写的那样。你需要更多的括号。首先正确缩进你的代码。并获得一个可以显示匹配括号的编辑器。
标签: php if-statement logic