Reputation: 17
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?
Upvotes: -1
Views: 1949
Reputation: 47903
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
Upvotes: -1
Reputation: 1582
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);
Upvotes: 3
Reputation: 67715
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. :)
Upvotes: 7