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

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 it does not already exist.

Some mb_ucfirst function testing and comparison to PHP’s ucfirst function:

Tests output looks following:

Share this post

9 Comments

  1. 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
    • Hi programmer,

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

      Reply
  2. 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
  3. 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 :)

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

    Reply
  5. 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
    • Hi javo,

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

      Reply
  6. 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
  7. Thanks man, very good code. big like! Good job! ;)

    Reply

Submit a Comment

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

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