Reputation: 21
I have a piece of code that I'm struggling with. I'm still on my first steps so it's entirely possible that some silly mistake is causing this. I want to turn each first character of each word into uppercase, but for some reason it is not working and I cannot get it figured out.
$split = explode(" ",$string);
foreach ($split as $word) {
if (ord($word[0]) >= 97 & ord($word[0]) <= 122){
$word[0] = chr(ord($word[0]) - 32);
}}
return $string;
}
Upvotes: 2
Views: 117
Reputation: 627
PHP provides in-built function that help you convert every word's first character to uppercase of the string without exploding and iterating through.
ucwords( $string );
EDIT: Let us include a sample to help you out what would be the output:
echo ucwords("Hi this is just a simple test of converting each word's first charater to uppercase!");
will return
Hi This Is Just A Simple Test Of Converting Each Word's First Charater To Uppercase!
Upvotes: 0
Reputation: 731
You should handle this a little differently.
Let's create our split first:
$words = explode(' ', $words_string);
Now let's loop through these words and remember their index by using the $key
param.
foreach($words as $index => $word) { //So we remember the key in the array using $k => $v
$words[$index] = ucfirst($word); //This will uppercase the first letter.
}
Upvotes: 3
Reputation: 6144
The reason why it's not working is explained in the question i've linked.
However in your case the solution is much more simple. You can just use ucwords() function or mb_convert_case() with MB_CASE_TITLE
if you work with multibyte strings.
Upvotes: 0