我目前正在努力实现的是将单词的第一个和最后一个字母大写。
目前这是我的功能:
function ManipulateStr($input){
return strrev(ucwords(strrev($input)));
}
然而,这只会将每个单词的最后一个字母改为大写,现在我正试图将我的想法集中在如何使每个单词的第一个字母也大写上。
一个例子:
输入:你好,我的朋友
输出:HellO MY FriendS
也许我将不得不使用子字符串?但是,考虑到我希望它适用于多个单词或单个单词,这将如何工作?
第一次使用strtolower
使字符串全部小写,然后使用函数ucwords
将第一个字符大写,然后再次使用strrev
并将ucwords
应用于其他第一个字符的大写。然后最后使用CCD_ 5来取回第一个和最后一个字符大写的原始字符串。
更新的功能
function ManipulateStr($input){
return strrev(ucwords(strrev(ucwords(strtolower($input)))));
}
如果你正在寻找一个比Frayne提供的功能快得惊人(快约20%),那么试试这个:
function ManipulateStr($input)
{
return implode(
' ', // Re-join string with spaces
array_map(
function($v)
{
// UC the first and last chars and concat onto middle of string
return strtoupper(substr($v, 0, 1)).
substr($v, 1, (strlen($v) - 2)).
strtoupper(substr($v, -1, 1));
},
// Split the input in spaces
// Map to anonymous function for UC'ing each word
explode(' ', $input)
)
);
// If you want the middle part to be lower-case then use this
return implode(
' ', // Re-join string with spaces
array_map(
function($v)
{
// UC the first and last chars and concat onto LC'ed middle of string
return strtoupper(substr($v, 0, 1)).
strtolower(substr($v, 1, (strlen($v) - 2))).
strtoupper(substr($v, -1, 1));
},
// Split the input in spaces
// Map to anonymous function for UC'ing each word
explode(' ', $input)
)
);
}