如何仅将格式为 "Town comma Initials" 的单个字符串的某些部分大写?

How do you uppercase only certain parts of a single string that's in format "Town comma Initials"?

我有一个位置字段,人们可以在其中输入他们想要的任何内容,但通常他们会输入 "Town, Initials" 格式的内容。例如,这些条目...

New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND

理想情况下会成为...

New York, NY
Columbia, SC
Charleston
Washington, DC
Bismarck, ND

显然我可以在字符串上使用 ucfirst() 来处理第一个字符,但这些是我不确定该怎么做的事情(如果它们完全可以做到的话)...

这很容易实现还是我需要使用某种正则表达式函数?

你可以简单地把它切碎并修复它。

<?php
$geo = 'New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND';
$geo = explode(PHP_EOL, $geo);

foreach ($geo as $str) {

    // chop
    $str = explode(',', $str);

    // fix
    echo 
    (!empty($str[0]) ? ucwords(strtolower(trim($str[0]))) : null).
    (!empty($str[1]) ? ', '.strtoupper(trim($str[1])) : null).PHP_EOL;
}

https://3v4l.org/ojl2M

尽管您不应该相信用户输入了正确的格式。取而代之的是找到所有状态的巨大列表并自动完成它们。也许像 https://gist.github.com/maxrice/2776900 - 然后验证它。