Reputation: 75
What I am currently trying to accomplish is to make the first and last letters of a word(s) uppercase.
Currently this is my function:
function ManipulateStr($input){
return strrev(ucwords(strrev($input)));
}
However this only changes the last letter of every word to uppercase, now I'm trying to wrap my mind around how to also get the first letter of every word capitalized.
An example:
input: hello my friends
output: HellO MY FriendS
Perhaps I will have to use a substr? But how would that work seeing as I want this to be applicable to either multiple words or a single word?
Upvotes: 3
Views: 1082
Reputation: 48100
Simply write a regex pattern with an alternation where a word boundary is either before or after an encountered word character.
Code: (Demo)
echo preg_replace_callback('/\b\w|\w\b/', fn($m) => strtoupper($m[0]), $string);
Alternatively, a conditional regex pattern can match an optional leading word boundary, then a word character, then if there was no word boundary before the word character enforce that the word character is immediately followed by a word boundary.
Code: (Demo)
echo preg_replace_callback('/(\b)?\w(?(1)|\b)/', fn($m) => strtoupper($m[0]), $string);
When either of the above snippets are fed:
$string = 'i must say hello to my handsome friends';
The output is:
I MusT SaY HellO TO MY HandsomE FriendS
Upvotes: 0
Reputation: 20757
If you are looking for a surprisingly faster function (~20% faster) than Frayne provided then try this:
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)
)
);
}
Upvotes: 0
Reputation: 9583
For the first time make your string all lower case by using strtolower
and then use the function ucwords
to capitalize the first character then use strrev
again and apply ucwords
for capitalize other first characters.
then finally use the strrev
for get back the original string with first and last character capitalized.
Updated Function
function ManipulateStr($input){
return strrev(ucwords(strrev(ucwords(strtolower($input)))));
}
Upvotes: 5