phpregexucfirst

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


I have a single location field where people can enter whatever they want, but generally they will enter something in the format of "Town, Initials". So for example, these entries...

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

would ideally become...

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

Obviously I can use ucfirst() on the string to handle the first character, but these are things I'm not sure how to do (if they can be done at all)...

Is this easily doable or do I need to use some sort of regex function?


Solution

  • You could simply chop it up and fix it.

    <?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

    Though you should not trust the user to enter the correct format. Instead find a huge list of all states and auto complete them in. Perhaps something like https://gist.github.com/maxrice/2776900 - then validate against it.