Replace the 1st letter which is lower case to upper case

[b]code[/b]
$myVar="abCd";

$myVar1 = str_replace('a','A', $myVar)

echo $myVar1;

[b]result[/b]

AbCd

The code above replaces the first letter of $myVar which is small letter “a” to the big letter “A”.
The result is what I wanted when I knew the first letter is “a”.
But How can I change it when I don’t know it?

If it is “a”, I like to change it “A”.
If it is “b”, I like to change it “B”.
If it is “c”, I like to change it “C”.
If it is “d”, I like to change it “D”.

: :

How can I replace the first letter of $myVar to the big letter?

[FONT=verdana]PHP has a built-in function to do this: ucfirst(). Pass it a string, and it returns the same string with the first letter capitalised.

Mike[/FONT]

I googled ‘php replace the 1st letter which is lower case to upper case’, and guess what appeared in position #4? The php manual with the function Mikl mentioned…

Please do your own research first.

I am not positive, but I think the OP wants to respect the existing UC letters, ie convert:


$myVar="abCd";

// to 

$myVar="AbCd";

Can you confirm @dotJoon; ?

Doesn’t ucfirst do exactly that?

Based on the manual, it seems it would.

Well, I take that back, now I never knew that. Crikey, I wonder where I have assumed that in my code :blush:

[FONT=verdana]

I am not positive, but I think the OP wants to respect the existing UC letters

That’s what I assumed. And, as Guido says, that’s what ucfirst() does.

If the function made the first letter upper case and the remaining letters lower-case, I’d expect it be called proper(). As far as I know, PHP doesn’t have one of those.

Mike[/FONT]

what about ucfirst()…?
:shifty:

[FONT=verdana]

Your point being?

Mike
[/FONT]

Off Topic:

lol guess I have been here longer than I thought! Does no one remember the trim() parody thread!!!

Very interesting thread! ucfirst, ucfirst, ucfirst! :smiley:

To be on topic I’ll add that ucfirst will not work with unicode character sets and if that is required then using mb functions is the way to go:


function mb_ucfirst($s) {
  if (strlen($s) > 0) {
    return mb_strtoupper(mb_substr($s, 0, 1)) . mb_substr($s, 1);
  } else {
    return '';
  }
}

Yes, it, the function ucfirst(), works fine. Thank you, Cups, as always.

Well I accept your thanks most graciously, but I have to say others have provided the answer.

I merely proved (again) to myself and others, that it is by trying to be a good member and stick your neck out and help others you expose yourself to correction.

When that happens I learn from it.

It can be humbling, but really, if there are any other passive readers and not participators out there, stick your neck out and jump in and provide your answers when you see the opportunity.

You will get things wrong and it might make you feel a bit daft for not knowing something but you will learn a lot, you’ll be helping others and you will make more friends. :slight_smile: