Converting the first letter of a string to a capital

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Converting the first letter of a string to a capital

Post by impulse() »

I'm sure I'm going to be needing

Code: Select all

strtoupper & substr
But at the moment my code is removing the first letter from each word and capitalising the rest of the word. Here's the code:

Code: Select all

$string = "this is the string i want to capitalise the first letter of each word on";

function upper($string) {

   $storage = array();
   $words = explode(" ", $string);

   foreach ($words as $test) {
     $storage[] = strtoupper(substr($test, 1));
    }
    print_r($storage);
}

upper($string);
But this is my unwanted output:

Array
(
[0] => HIS
[1] => S
[2] => HE
[3] => TRING
[4] =>
[5] => ANT
[6] => O
[7] => APITALISE
[8] => HE
[9] => IRST
[10] => ETTER
[11] => F
[12] => ACH
[13] => ORD
[14] => N
)
Any pointers please?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

That was too easy :)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

They usually are. If you search years ago for my older posts you might come across one where I spent about 45 lines of code attempting to fetch the name portion of the current file that I was in. :oops:

We come here to learn. You learned. We are both golden. :D
Z3RO21
Forum Contributor
Posts: 130
Joined: Thu Aug 17, 2006 8:59 am

Post by Z3RO21 »

Same here, I needed the same functionality so I wrote all these lines to make the first word capital. Then reading PHP.net I basicaly smacked myself.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

I would venture to say that almost everything that we want to do with data manipulation, numerics and files, has already been done either in the core or by someone. The PHP team, although making this a bit inconsistent with the core functions, has included quite an array of functionality in the core.
Post Reply