开发者

Make all the words in a string with 3 characters or less completely uppercase

I trying to accomplish the following:

$string = "i want to convert this string to the开发者_JS百科 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?


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. :)


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜