user198989
user198989

Reputation: 4665

Ucfirst doesnt work on non-english characters

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 ?

Upvotes: 5

Views: 5641

Answers (5)

Jens Törnell
Jens Törnell

Reputation: 24768

I made it a oneliner.

function mb_ucfirst($str) {
  return mb_strtoupper(mb_substr($str, 0, 1)).mb_substr($str, 1, mb_strlen($str));
}

Upvotes: 2

Irek Kubicki
Irek Kubicki

Reputation: 57

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

Upvotes: 1

julp
julp

Reputation: 4010

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);

Upvotes: 9

user198989
user198989

Reputation: 4665

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);
}

Upvotes: 4

René Höhle
René Höhle

Reputation: 27295

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.

Upvotes: 2

Related Questions