PHP string-formatting: 大写前三个字母,添加连字符并将下一个单词的首字母大写以进行 strpos() 匹配
PHP string-formatting: Capitalize first three letters, add hyphen and capitalize first letter of next word for strpos() matches
我正在尝试对上传到数据库中的字符串列表进行一致的格式化,这些字符串很可能会继续被错误地格式化。我检查了以 "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...
}
有些是Us/Usw或us/usw,但都只需要大写,后面跟一个连字符,下一个单词的首字母大写。我对 PHP 中的字符串解析和格式化不是很熟悉,所以非常感谢任何帮助!
你可以选择 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));
}
此函数将return除第一个字母外的第二部分小写。如果你想保持原样,只需将子字符串部分中的 $s_low
替换为 $s
。
我正在尝试对上传到数据库中的字符串列表进行一致的格式化,这些字符串很可能会继续被错误地格式化。我检查了以 "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...
}
有些是Us/Usw或us/usw,但都只需要大写,后面跟一个连字符,下一个单词的首字母大写。我对 PHP 中的字符串解析和格式化不是很熟悉,所以非常感谢任何帮助!
你可以选择 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));
}
此函数将return除第一个字母外的第二部分小写。如果你想保持原样,只需将子字符串部分中的 $s_low
替换为 $s
。