Uppercase first word in a string or sentence

May 24th, 2009 by Alex M Leave a reply »

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:

1
2
3
4
5
6
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:

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

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

Advertisement

6 comments

  1. Chad says:

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

  2. Alex M says:

    Hi Chad,

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

  3. Chad says:

    correct sorry

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

  4. Brett says:

    Could just use php’s inbuilt function..

    http://php.net/manual/en/function.ucfirst.php

  5. Alex M says:

    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.”

  6. Mitch says:

    Full proof? I think you mean foolproof, fool :-)

Leave a Reply