我花了好几个小时试图让我的代码工作,它是一个if / elses的老鼠窝。基本上我想针对这两个数组检查国家名称:
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("eire","hispaniola");
就是这样。
它让我发脾气,说实话,我很尴尬地向你展示我的代码。让我们说它有2个if语句,2个else语句和2个foreach循环。它是一个盛开的混乱,我希望有人可以通过向我展示这样做的好方法让我感到沮丧吗?我希望有一种方法只使用一行代码,或类似令人作呕的东西。 谢谢。
答案 0 :(得分:3)
这建立在@ sgehrig的答案之上,但请注意例外情况的变化:
//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("the eire","the hispaniola");
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The ' . $country;
} else if (in_array($countryKey, $exceptions)) {
$country = substr($country, 4);
}
答案 1 :(得分:2)
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The' . $country;
} else if (in_array($countryKey, $exceptions) && stripos($country, 'the ') === 0) {
$country = substr($country, 4);
}
答案 2 :(得分:1)
最简单的方法是将其拆分为两个步骤,对于与第一个列表匹配的国家/地区添加“the”,然后只要删除它,如果匹配第二个列表中的字词。
答案 3 :(得分:1)
如果国家/地区名称包含在字符串(strpos)中,为什么要简单测试:
",bahamas,island,kingdom,republic,maldives,netherlands,isle of man,ivory,philippines,seychelles,usa,"
(注意开头和尾随',')
它比正则表达式更快:如果您的“,国家/地区名称”是该字符串,请添加“THE”,否则将其删除。
答案 4 :(得分:1)
我相信你正在寻找这样的东西:
if(in_array($country, $keywords)) {
// add 'the'
} elseif(in_array($country, $exceptions)) {
// remove 'the'
}
答案 5 :(得分:1)
in_array()是你的朋友。无需为它循环。