Uppercase first word in a string or sentence

I have just had a task which requires making the first word of a string uppercase. I have come up with quite an easy and simple solution and thought I would share it with you.

An example input string might look like “HELLO world. This is a test.” The required output is “Hello world. This is a test.”

Below is a function which will help you achieve this:


function uc_first_word($string) {
    $s = explode(' ', $string);
    $s[0] = ucfirst(strtolower($s[0]));
    $s = implode(' ', $s);
    return $s;
}

Now I know this function isn’t full proof, and assumes that the string you are passing actually contains words. If the first word was a roman numeral for example, this function would not work (ie VI would become Vi).

Usage of this function is quite easy:

$string = uc_first_word('HELLO world. This is a test.');

I hope that this might help someone searching for a similar solution.

8 thoughts to “Uppercase first word in a string or sentence”

  1. Hi Chad,

    Your solution would not work in the test case “HELLO world”. Your function would still return “HELLO world”.

  2. correct sorry

    function uc_first_word ($string)
    {
    return strtoupper(substr($string,0,1)).strtolower(substr($string,1));
    }

  3. Hi Brett,

    The function does use PHP’s ucfirst(), but it does not work by itself.

    Using our test string – “HELLO world. This is a test.”, if we just used ucfirst it would return “HELLO world. This is a test.” still, as the first word is all caps.

    If we also used ucfirst(strtolower(“HELLO world. This is a test.”)) we would still have a problem. This would return “Hello world. this is a test.”

  4. The problem is ” …requires making the first word of a string uppercase.”

    The example provided is of the OUTPUT required above, not the INPUT. The example input string has the first word in UPPERCASE and so therefore should _not_ be changed.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.