If Not True Then False

PHP mb_ucfirst Make a String’s First Character Uppercase-Multibyte (UTF-8) Function - Comment Page: 1

PHP’s ucfirst function is very usefull when you want to change words first letters to uppercase and other letters to lowercase. Currently on PHP does not have a multibyte (UTF-8) version of ucfirst function. So I decided write my own multibyte mb_ucfirst function. Perhaps the multibyte version of ucfirst function is added later on PHP, so that’s why is better add this function only if...
Categories:

11 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Input your comment.
help

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Input your name.

programmer

Nice function. Too bad none of your example strings contains multibyte characters, so it doesn’t really prove that your function would work with all these accents, rings, umlauts, etc.

reply Reply
JR

Hi programmer,

I added example with multibyte characters and of course you could try it with your own multibyte characters.

reply Reply
El RIDO

Thanks for sharing! Just in case somebody else stumbles on this page searching for something slightly different like me: mb_convert_case() has a flag MB_CASE_TITLE which is a faster way to make only the first character of every word upper case, then trying to split the string and then use the above mb_ucfirst() function on every segment.

This would result in the string “YeT MORE teSTing” becoming “Yet More Testing” instead of “Yet more testing”.

http://www.php.net/manual/en/function.mb-convert-case.php

reply Reply
Raziel Anarki

Hi! just stumbled upon this in a time of need via google, thanks for that! :)

however, when adjusting it to fit our coding style, i did notice it could be rewritten to be somewhat more simple, so i did some refactoring and come up with this iteration.
thought i’d share, hope you’ll like it :)


if (!function_exists('mb_ucfirst'))
{
function mb_ucfirst ($str, $encoding = "UTF-8", $lower_str_end = false)
{
$first_letter = mb_strtoupper (mb_substr ($str, 0, 1, $encoding), $encoding);
$str_end = mb_substr ($str, 1, mb_strlen ($str, $encoding), $encoding);

return $first_letter.($lower_str_end ? mb_strtolower ($str_end) : $str_end);
}
}

reply Reply
Alecksey

Thanks. It works for me fine. I was confused that this functions absent in mbstrings.

reply Reply
javo

Hi, programmer, I’ve tested the function with accents and it works great.

This function is a really nice work.

To JR thanks for sharing this. It was really usefull to me :)

reply Reply
JR

Hi javo,

Thanks, very nice to hear that this is useful for you! :)

reply Reply
david96

this astuce is very good for me. I’ve simply changed : function mb_ucfirst($str, $encoding = “iso-8859-1”, $lower_str_end = true)

Big thanks :)

reply Reply