对于php getText的集合并避免键入定义错误的合适结构是什么



问题

我开始在与PHP相关的文件中为I18N实现GetText。即使网络上有很多教程,我也很难找到一个清晰的答案在脚本中将setLocale放置在哪里?。每个人似乎都将其定位在脚本的开头。

示例

getText在以下PHP功能上效果很好,但是我对其他PHP功能有问题(请参见下面的评论):

$category = LC_ALL;
$locale = "fr_FR";
$domain = "messages";
$lat = 43.848977; // float with a point separator
setlocale( $category, "$locale" );
putenv( "$category=$locale" );
bindtextdomain( $domain, "./Locale" );
bind_textdomain_codeset( $domain, 'UTF-8' );
echo gettext("sample text"); // works OK
// The issue starts here
$center_lat = filter_var( $lat, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); 
// The float $latitude is interpreted as string due to comma in French,
// filter_var do interpret as a float anymore and $center_lat gives something like 43848977 instead of 43,848977

我想的解决方案

i虽然我必须每次调用getText:

时我必须做这样的事情(几乎)
$userLocale = setlocale( $category, 0 ); // current setting is returned
echo gettext( "sample text" );
setlocale( $category, $userLocale );
// SCRIPT RESUME
$userLocale = setlocale( $category, 0 ); // current setting is returned
echo gettext( "other text" );
setlocale( $category, $userLocale );

我在getText的官方手册中没有找到完整的文件示例

中的明确答案

我尝试了

我尝试了不成功的类型铸造:

$center_lat = filter_var( (float) $lat, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); 

问题

我的解决方案是避免出乎意料的错误(无论是类型铸件还是其他)?

filter_var()通常用于检查您的Web表单输入,其中我认为输入值在字符串中给出。在什么情况下,它需要通过Filter_var()检查float?

无论如何,要检查语言环境格式的号码,您可以使用php_intl扩展名将法语编号字符串转换为常规数字,然后filter_var()应该工作。

if (!class_exists('NumberFormatter')) {
    exit ('You need to install php_intl extension.');
}
$category = LC_ALL;
$locale = "fr_FR";
$domain = "messages";
$lat = '43,848977';
setlocale( $category, "$locale" );
putenv( "$category=$locale" );
bindtextdomain( $domain, "./Locale" );
bind_textdomain_codeset( $domain, 'UTF-8' );
$localeFormatter = new NumberFormatter($locale, NumberFormatter::DECIMAL); 
$center_lat = filter_var(
    $localeFormatter->parse($lat),
    FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION
);
echo $center_lat . PHP_EOL;

最新更新