Make first character of all the words in a string uppercase; if word has 3 characters or less, convert to ALLCAPS

1.9k views Asked by At

I trying to accomplish the following:

$string = "i want to convert this string to the following";

and convert it to something like this:

echo $string;
// I Want TO Convert This String TO THE Following

Thus: Capitalize the First Letter of All Words in a string and if a word is 3 characters or less, make the whole word Capitalized in the string. How cant this be done with PHP?

3

There are 3 answers

1
lszrh On

you could explode() your string and loop over it to check the length:

$array = explode(' ', $string);
foreach($array as $k => $v) {
    if(strlen($v) <= 3) {
        $array[$k] = strtoupper($v); //completely upper case
    }
    else {
        $array[$k] = ucfirst($v); //only first character upper case
    }
}
$string = implode(' ', $array);
1
netcoder On

A quick way (with regex):

$new_string = preg_replace_callback('/\b\w{1,3}\b/', function($matches){
   return strtoupper($matches[0]);
}, $string);

EDIT:

Didn't see you wanted to ucfirst the rest. This should do it:

$new_string = ucwords($new_string);

You can also combine them. :)

1
mickmackusa On

If a matched word character is followed by 1 or 2 word characters and then no more word characters, then convert all matched characters to uppercase; otherwise only convert the first word character to uppercase.

Code: (Demo)

$string = "i want to convert this string to the following";

echo preg_replace_callback(
         '/\b\w(?:\w{1,2}\b)?/',
         fn($m) => strtoupper($m[0]),
         $string
     );
// I Want TO Convert This String TO THE Following