Hi everyone,
I have the following code snippet which is used to perform some case modification of a sentence. It takes a sentence and then capitalizes the first letter of every word of the sentence.
It has a few exceptions:
- It will not capitalize anything defined in $exclude_words
- It will not remove the all-caps from the words defined in $capital_words. In fact if a word that is defined in $capital_words is not typed in all caps, it will convert that word to all caps.
- It will convert anything that is typed in all-caps and is longer than the character length defined in $max_length to uppercase first letter and lowercase for the rest of the word.
The issue that I am having is this:
If the letter ‘i’ is entered in lowercase such as in the sentence “i really like cake with a tiny bit of icing” it will capitalize the letter ‘i’ which it should do but then it will also capitalize every other instance of the letter ‘i’ anywhere it occurs. The output will be: “I Really LIke Cake WIth a TIny BIt of IcIng”.
The occurrences of ‘i’ inside the word should obviously not be capitalized but I’m not sure how to solve this. I am a beginner and just trying my best to learn as I go along.
Thank you for any help anyone can provide!
[php]<?php
$string = “how many words can i type if I have to keep typing words over and over again, this might be interesting!”; // Your input string
$exclude_words = array(“the”,“a”,“of”,“and”,“is”); // Exclude analyzing these words
$capital_words = array(“brb”,“lol”); // Capital exclusives (leave in lowercase in array)
$max_length = 5; // Maximum word length, anything over is case-lowered
$parts = explode(" ",$string);
foreach ($parts as $word) {
if (!in_array(strtolower($word),$exclude_words)) {
$old_word = $word;
$first_letter = substr($word,0,1);
if (strlen($word) >= $max_length && !in_array(strtolower($word),$capital_words)) { $word = strtolower($word); }
if (in_array(strtolower($word),$capital_words)) { $word = strtoupper($word); }
$newWord = strtoupper($first_letter).substr($word,1);
$string = str_replace($old_word,$newWord,$string);
}
}
echo $string; // This should output the string
?>[/php]