phpstringuppercase

How to make first and last letters capital in a word (therefore multiple strings) php


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?


Solution

  • 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)))));
    }