Reputation: 21
I need a method to capitalize every first letter of a word. This is what i got so far and it is working for almost every string...but it fails on this one "WELLNESS & RENOMME".
// method in stringModify Class
function capitalizeWords($words, $charList) {
$capitalizeNext = true;
for ($i = 0, $max = strlen($words); $i < $max; $i++) {
if (strpos($charList, $words[$i]) !== false) {
$`capitalizeNext` = true;
} else if ($capitalizeNext) {
$capitalizeNext = false;
$words[$i] = strtoupper($words[$i]);
}
}
return $words;
}
// Calling method
$stringModify->capitalizeWords("WELLNESS & RENOMME", " -&");
I hope someone can help me out...i tried for 1,5 hours now and don't have a clue. Thanks in advance for any tips or hints.
ucwords() uses " " as delimitor and i want to use "-" for example too.
thanks to you all for you solutions. i will go to bed now, its 7 in the morning here. :D i will see which solution i like best when i wake up and then tell you which one i choosed.
it seems like all the functions are returning "wellness &Amp; Renomme" or "wellness & Renomme". is it possible that something in my php.ini is messed up?
Upvotes: 2
Views: 778
Reputation: 1242
For converting the first letter capital in all sentence use the below code.
Ex)
$string = strtolower($string);
echo preg_replace('/(^|[\.!?]"?\s+)([a-z])/e', '"$1" . ucfirst("$2")', $string);
?>
Upvotes: 0
Reputation: 468
function cb($word){ return ucwords(strtolower($word[0])); }
var_dump(preg_replace_callback('@[A-z]+@i','cb','TESTING-TESTING / TESTING & TEST / testing*&^123!&%&*TEST'));
Upvotes: 1
Reputation: 54719
I'm confused at what exactly you're trying to do. PHP already has a ucwords()
function that can do this and I don't see any difference in what you're doing... If you're capitalizing the first letter of each word, do delimiters make any difference? Does it matter at all that there's a '&' between the two words?
Edit: I think I understand now. I assume the only problem you're having is that you can't tell it's uppercasing the text because it's already all uppercased, all you need to do is lowercase it first. I also changed it to completely get rid of the 'next character' thing, it was unnecessary. If you find a match, just change the next character to uppercase. Try this:
// method in stringModify Class
function capitalizeWords($words, $charList) {
$words = strtolower($words); // lowercase everything that isn't capitalized
for ($i = 0; $i < strlen($words); $i++) {
if (strpos($charList, $words[$i]) !== false) $words[$i+1] = strtoupper($words[$i+1]);
}
return $words;
}
// Calling method
$stringModify->capitalizeWords("WELLNESS & RENOMME", " -&");
Upvotes: 1