用字符串分解,在数组中搜索 return 它的值

Explode with string, search in array and return it's value

我正在尝试将 Country slug 转换器转换为简称。所以我创建了这个函数:

<?php 
function convertCountry( $countrySlug ) {
    $countries = "Andorra: AR|United-Arab-Emirates: UAE|Afghanistan: AFG|Antigua-And-Barbuda: AAB|Anguilla: ANG|Albania: ALB|Armenia: ARM";

    $countryArray = explode('|', $countries);

    return array_search($countrySlug, $countryArray);
}

echo convertCountry('United-Arab-Emirates');
?>

必须打印 UAE 但不起作用。

array_search 会找到相同的文本。在你的情况下,我认为我们应该使用 strpos.

function strpos_array($countryArray, $countrySlug) {
    if (is_array($countryArray)) {
        foreach ($countryArray as $country) {
            if (($pos= strpos($country, $countrySlug)) !== false) {
                return str_replace($countrySlug.': ', '', $country);
            };
        }
    }
    return false;
}

function convertCountry($countrySlug) {
    $countries = "Andorra: AR|United-Arab-Emirates: UAE|Afghanistan: AFG|Antigua-And-Barbuda: AAB|Anguilla: ANG|Albania: ALB|Armenia: ARM";

    $countryArray = explode('|', $countries);

    return strpos_array($countryArray, $countrySlug);
}
echo convertCountry('United-Arab-Emirates');
//This will print UAE