PHP: Uygun başlık halinde bir şehir, eyalet, ülke dize Transform

2 Cevap php

Ben gibi şehir, eyalet, ülke dizeleri var:

NEW YORK, NY, US
REDMOND, WA, US
US
HONG KONG
CALGARY, CA
E. SYRACUSE, NY, US

Ben onların uygun durumda (; vs New York, NY, ABD) onları dönüştürmek istiyorum. Hızlı bir şekilde PHP bunu yapmak nedir?

2 Cevap

Bir sözlük olmadan her zaman orada bazı kenar durumlar olabilir, bu yüzden bu yaklaşım iyi olacağını düşünüyorum

vinko@parrot:~$ cat cap.php
<?php

$list = "NEW YORK, NY, US
REDMOND, WA, US
US
HONG KONG
CALGARY, CA
E. SYRACUSE, NY, US";

$countries = array("HONG KONG", "US", "CA");
$states = array("NY","WA");

$list = split("\n",$list);

$out = "";
foreach ($list as $line) {
        list($first,$second,$third) = split(",",$line);

        //Here you check in a dictionary for country/state to
        //like this:

        if (!in_array($first,$countries) && !in_array($first,$states)) {
                $first = ucwords(strtolower($first));
        }
        if ($third) { $out.= $first.",".$second.",".$third; }
        else if ($second && !$third) { $out.= $first.",".$second; }
        else { $out.= $first; }
        $out.= "\n";
}
echo $out;
?>
vinko@parrot:~$ php cap.php
New York, NY, US
Redmond, WA, US
US
HONG KONG
Calgary, CA
E. Syracuse, NY, US