How to make all 3 characters or less words in a string uppercase in PHP

2 Answers

0 votes
$string = 'php java css c python sql cpp go csharp';

$array = explode(' ', $string);

foreach ($array as $key => $val) {
    if (strlen($val) <= 3) {
        $array[$key] = strtoupper($val); 
    }
    else {
        $array[$key] = $val; 
    }
}

$string = implode(' ', $array);

echo $string;





/*
run:

PHP java CSS C python SQL CPP GO csharp

*/

 



answered Jul 11, 2023 by avibootz
0 votes
$string = 'php java css c python sql cpp go csharp';

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

echo $string;





/*
run:

PHP java CSS C python SQL CPP GO csharp

*/

 



answered Jul 11, 2023 by avibootz
...