Search code examples
phpstringparsingstring-formattingphp-7

PHP string-formatting: Capitalize first three letters, add hyphen and capitalize first letter of next word for strpos() matches


I'm attempting to consistently format a list of strings that were inconsistently uploaded into the database and will likely continue to be poorly formatted. I have a check for strings that begin with "us" or "usw":

if (strpos($string, 'us') !== false ||
    strpos($string, 'usw' !== false)
    ) {
    // Format string so that the us/usw are uppercase and there is a hyphen after. 
    // Sample strings: ussetup, uswadmin, Uswonsite, etc.
    // Ideal return for above: US-Setup, USW-Admin, USW-Onsite...
}

Some are Us/Usw or us/usw, but all just need to be uppercase, followed by a hyphen and the first letter of the next word capitalized. I'm not very familiar with parsing and formatting strings in PHP, so any help would be greatly appreciated!


Solution

  • You could maybe go for preg_replace_callback, like this:

    $string = "uswsetup"; // example input string
    $result = preg_replace_callback("/^(usw?)-?(.)/mi", function ($m) {
        return strtoupper("$m[1]-$m[2]");
    }, $string); 
    
    echo $result; // USW-Setup