Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ucfirst doesnt work on non-english characters [duplicate]

Tags:

php

ucfirst

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 ?

like image 480
user198989 Avatar asked Dec 07 '22 00:12

user198989


1 Answers

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);
like image 144
julp Avatar answered Dec 23 '22 21:12

julp