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.