utf-8 Carbon 格式本地化的错误字符

Bad characters in utf-8 Carbon formatLocalized

我知道这有很多,但它不起作用,我安装了语言。

locale -a | grep es
 es_ES
 es_ES.ISO8859-1
 es_ES.ISO8859-15
 es_ES.UTF-8

我已经设置为utf-8

\Carbon\Carbon::setUtf8(true);
setlocale(LC_ALL, 'es_ES.UTF-8');
$game_date = $date->formatLocalized('%A %d %B %Y %H %M %p');

我的 html

中有 utf-8 标签
<meta charset="utf-8">

但我仍然输入错误的字符。

"sábado" - "miércoles"

我在尝试使用 sk_SK.UTF-8 语言环境时遇到了同样的问题。帮助我解决问题的是删除代码的 \Carbon\Carbon::setUtf8(true); 部分。

但为什么会这样呢?首先,关于 setUtf8 函数的 Carbon 文档是这样说的:

Some languages require utf8 encoding to be printed (locale packages that does not ends with .UTF8 mainly). In this case you can use the static method Carbon::setUtf8() to encode the result of the formatLocalized() call to the utf8 charset.

检查 Carbon 的源代码后,如果我们之前使用已经提到的 [=15] 将变量 utf8 设置为 true,formatLocalized() 函数会调用 PHP 库中的 utf8_encode() 函数=]. Carbon source on GitHub

return static::$utf8 ? utf8_encode($formatted) : $formatted;

因为您的语言环境已经配置为使用 UTF-8 标准,进一步的 php 编码会弄乱格式化的字符串。

我认为如果您想使用 Carbon 将您的字符串格式化为 utf8,您必须在使用 setLocale() 设置您的语言环境时首先摆脱 UTF-8 编码。但是,我会坚持删除 Carbon 函数并使用正确的语言环境。

TL;DR

使用正确的语言环境和 UTF-8 编码,例如es_ES.UTF-8 或尝试使用没有 UTF-8 编码的语言环境并依赖 \Carbon\Carbon::setUtf8(true);utf8_encode() 函数。我建议第一个选项。希望这对您有所帮助:)