5

I'm trying to make the first letter uppercase in a string. It works fine for english letters, but unfortunetely, it doesn't work on non-english chars, for example

echo ucfirst("çağla");

What is the correct way to make ucfirst work properly on all words including non-english chars ?

user198989
  • 4,574
  • 19
  • 66
  • 95
  • 2
    Did you read the documentation page on `ucfirst?` it uses the locale language. Also [the first comment on the documentation](http://php.net/manual/en/function.ucfirst.php#57298) gives you the perfect work around. – Ohgodwhy Sep 08 '14 at 17:36

5 Answers5

9

For a single word, the right way is: mb_convert_case with MB_CASE_TITLE in second argument.

mb_internal_encoding('UTF-8');

echo mb_convert_case('çağla', MB_CASE_TITLE);

Because it depends on the charset and locale: some languages distinguish uppercase to titlecase. Here, titlecasing is more appropriate.

An example: the digram character dz. Which becomes DZ in uppercase but Dz in titlecase. This is not the same thing.

Note: mb_convert_case + MB_CASE_TITLE alone is equivalent to ucwords. The strict equivalent of ucfirst would be:

return mb_convert_case(mb_substr($str, 0, 1), MB_CASE_TITLE) . mb_substr($str, 1);
julp
  • 3,860
  • 1
  • 22
  • 21
4

Thanks, I finally found this working function as Stony's suggestion.

function myucfirst($str) {
    $fc = mb_strtoupper(mb_substr($str, 0, 1));
    return $fc.mb_substr($str, 1);
}
user198989
  • 4,574
  • 19
  • 66
  • 95
2

In newer PHP-Versions PHP work internally with UTF-8. So if you have a string that is not UTF-8 you cat get problems in some functions like htmlspecialchars for example.

Perhaps here is it a same problem. You can try to convert your string to utf-8 first with utf8_encode.

I think the default language is C.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

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

If you scroll down you get a function to convert it.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
2

I made it a oneliner.

function mb_ucfirst($str) {
  return mb_strtoupper(mb_substr($str, 0, 1)).mb_substr($str, 1, mb_strlen($str));
}
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
1

please try $string = mb_strtoupper($string[0]) . mb_substr($string, 1);

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105