简体   繁体   English

PHP字符串格式:大写的前三个字母,添加连字符,并为strpos()匹配的下一个单词的首字母大写

[英]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": 我检查了以“ us”或“ 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. 有些是Us / Usw或us / usw,但都只需要大写,后跟一个连字符和下一个单词的首字母大写。 I'm not very familiar with parsing and formatting strings in PHP, so any help would be greatly appreciated! 我对使用PHP解析和格式化字符串不是很熟悉,因此非常感谢您的帮助!

You could maybe go for preg_replace_callback , like this: 您可能会喜欢preg_replace_callback ,如下所示:

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

echo $result; // USW-Setup
function formatString($s)
{
    $s_low = strtolower($s) ; // full string in lower case

    if( substr($s_low, 0, 3) == 'usw' )
        return 'USW-' . ucfirst(substr($s_low, 3)) ;
    elseif( substr($s_low, 0, 2) == 'us' )
        return 'US-' . ucfirst(substr($s_low, 2));
}

This function will return the second part in lowercase, except for the first letter. 此函数将以小写形式返回第二部分,但第一个字母除外。 If you want to keep it intact, just replace $s_low per $s in the substring parts. 如果要保持原样,只需在子字符串部分替换$s_low per $s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM