问题
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 ?
回答1:
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);
回答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.
回答3:
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);
}
回答4:
please try $string = mb_strtoupper($string[0]) . mb_substr($string, 1);
回答5:
I made it a oneliner.
function mb_ucfirst($str) {
return mb_strtoupper(mb_substr($str, 0, 1)).mb_substr($str, 1, mb_strlen($str));
}
来源:https://stackoverflow.com/questions/25729900/ucfirst-doesnt-work-on-non-english-characters