[英]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));
}
此函數將以小寫形式返回第二部分,但第一個字母除外。 如果要保持原樣,只需在子字符串部分替換$s_low
per $s
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.