如何使单词中的第一个和最后一个字母大写(因此多个字符串)php
How to make first and last letters capital in a word (therefore multiple strings) php
我目前正在尝试完成的是将单词的第一个和最后一个字母大写。
目前这是我的功能:
function ManipulateStr($input){
return strrev(ucwords(strrev($input)));
}
然而,这只会将每个单词的最后一个字母更改为大写,现在我正在思考如何将每个单词的第一个字母也大写。
一个例子:
input: hello my friends
output: HellO MY FriendS
也许我必须使用 substr?但是,如果我希望它适用于多个单词或单个单词,那将如何工作?
第一次使用 strtolower
使字符串全部小写,然后使用函数 ucwords
将第一个字符大写,然后再次使用 strrev
并应用 ucwords
用于将其他第一个字符大写。
然后最后使用 strrev
取回第一个和最后一个字符大写的原始字符串。
更新函数
function ManipulateStr($input){
return strrev(ucwords(strrev(ucwords(strtolower($input)))));
}
如果您正在寻找比 提供的更快的函数(快约 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)
)
);
}
我目前正在尝试完成的是将单词的第一个和最后一个字母大写。
目前这是我的功能:
function ManipulateStr($input){
return strrev(ucwords(strrev($input)));
}
然而,这只会将每个单词的最后一个字母更改为大写,现在我正在思考如何将每个单词的第一个字母也大写。
一个例子:
input: hello my friends
output: HellO MY FriendS
也许我必须使用 substr?但是,如果我希望它适用于多个单词或单个单词,那将如何工作?
第一次使用 strtolower
使字符串全部小写,然后使用函数 ucwords
将第一个字符大写,然后再次使用 strrev
并应用 ucwords
用于将其他第一个字符大写。
然后最后使用 strrev
取回第一个和最后一个字符大写的原始字符串。
更新函数
function ManipulateStr($input){
return strrev(ucwords(strrev(ucwords(strtolower($input)))));
}
如果您正在寻找比
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)
)
);
}