跳转到内容

国际化


概览

Phalcon 是用 C 语言编写的 PHP 扩展。有一个PECL扩展,为 PHP 应用程序提供国际化功能,名为intl。其文档可以在官方PHP 手册.

Phalcon 不提供此功能,因为创建这样的组件会复制现有的代码。

在下面的例子中,我们将展示如何将intl扩展的功能集成到 Phalcon 驱动的应用程序中。

注意

本指南并非旨在成为该intl扩展的完整文档。请访问该扩展的文档参考页面。

查找最佳可用的语言环境

有几种方法可以使用intl来查找最佳可用的语言环境。其中一种方法是检查 HTTPAccept-Language标头:

<?php

use Locale;

$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

// Locale could be something like 'en_GB' or 'en'
echo $locale;

下面的方法返回一个标识符对应的语言环境。它用于从 Locale API 中获取特定语言、文化和区域性行为。

标识符示例包括:

标识符 描述
en-US (英语,美国)
ru-RU (俄语,俄罗斯)
zh-Hant-TW (中文,繁体字,台湾)
fr-CA, fr-FR (法语,分别适用于加拿大和法国)

基于语言环境的格式化消息

创建本地化的应用程序的一部分是生成连接的、与语言无关的消息。MessageFormatter允许生成这些消息。

根据某些语言环境格式化数字并打印:

<?php

use MessageFormatter;

// € 4 560
$formatter = new MessageFormatter('fr_FR', '€ {0, number, integer}');
echo $formatter->format([4560]);

// USD$ 4,560.5
$formatter = new MessageFormatter('en_US', 'USD$ {0, number}');
echo $formatter->format([4560.50]);

// ARS$ 1.250,25
$formatter = new MessageFormatter('es_AR', 'ARS$ {0, number}');
echo $formatter->format([1250.25]);

使用时间和日期模式进行消息格式化:

<?php

use MessageFormatter;

$time   = time();
$values = [7, $time, $time];

// 'At 3:50:31 PM on Apr 19, 2015, there was a disturbance on planet 7.'
$pattern   = 'At {1, time} on {1, date}, there was a disturbance on planet {0, number}.';
$formatter = new MessageFormatter('en_US', $pattern);
echo $formatter->format($values);

// 'À 15:53:01 le 19 avr. 2015, il y avait une perturbation sur la planète 7.'
$pattern   = 'À {1, time} le {1, date}, il y avait une perturbation sur la planète {0, number}.';
$formatter = new MessageFormatter('fr_FR', $pattern);
echo $formatter->format($values);

语言环境敏感的比较

The Collator类提供了字符串比较功能,并支持适当的语言环境敏感排序顺序。请参阅以下示例以了解此类的用法:

<?php

use Collator;

// Create a collator using Spanish locale
$collator = new Collator('es');

// Returns that the strings are equal, in spite of the emphasis on the 'o'
$collator->setStrength(Collator::PRIMARY);

var_dump(
    $collator->compare('una canción', 'una cancion')
);

// Returns that the strings are not equal
$collator->setStrength(Collator::DEFAULT_VALUE);

var_dump(
    $collator->compare('una canción', 'una cancion')
);

转写

Transliterator提供字符串的转写功能:

<?php

use Transliterator;

$id = 'Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();';
$transliterator = Transliterator::create($id);

$string = "garçon-étudiant-où-L'école";
echo $transliterator->transliterate($string); // garconetudiantoulecole
无噪 Logo
无噪文档
25 年 6 月翻译
文档源↗