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.
function uc_first_word ($string)
{
return strtoupper(substr($string,0,1)).substr($string,1)
}
Hi Chad,
Your solution would not work in the test case “HELLO world”. Your function would still return “HELLO world”.
correct sorry
function uc_first_word ($string)
{
return strtoupper(substr($string,0,1)).strtolower(substr($string,1));
}
Could just use php’s inbuilt function..
http://php.net/manual/en/function.ucfirst.php
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.”
Full proof? I think you mean foolproof, fool
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.