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