PHP: Convert city, state, country to appropriate header
function title_case($val) {
return mb_convert_case($val[0], MB_CASE_TITLE, "UTF-8");
}
$locs = array(
'NEW YORK, NY, US',
'REDMOND, WA, US',
'US',
'HONG KONG',
'CALGARY, CA',
'E. SYRACUSE, NY, US',
);
foreach ($locs as &$loc) {
$loc = preg_replace_callback( '/\b\w{3,}\b/', "title_case", $loc);
}
print_r($locs);
// Array
// (
// [0] => New York, NY, US
// [1] => Redmond, WA, US
// [2] => US
// [3] => Hong Kong
// [4] => Calgary, CA
// [5] => E. Syracuse, NY, US
// )
a source to share
What do you mean by doing the right thing? I have a feeling that I am missing something as far as you need it, so it would be nice if you could figure out exactly what this data is and how you want to handle it.
You can use ucfirst
to make the first letter of each word uppercase, and you can use explode
to split the string into appropriate segments:
$str = "NEW YORK, NY, US";
list($city, $state, $country) = explode(',', $str);
$city = ucfirst(strtolower($city));
In the examples you have provided, you will not need to do anything to specify the country and country, although there is strtoupper
if you want them to be capitalized.
I also notice that there are a few strings that only have a country ("USA"), and some that only have a city ("HONG KONG"), there is no reliable way to determine what the string contains. You can try matching it against a list of countries and cities, etc., but it looks like whatever solution you come up with will be a guessing game at best.
a source to share
There will always be some edge cases without a dictionary, so I think this approach would be the best
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
a source to share