原文地址: https://www.sitepoint.com/localization-demystified-understanding-php-intl/
大多数应用程序执行场可以识别类似处理文本,日期,时区等的操作。而 PHP Intl 的扩展功能可提供一个良好的 API ,用以连接广为人知的 ICU 库的功能。
安装
此扩展功能默认安装在 PHP 5.3 及以上的版本,你可以通过以下命令进行查找:
php -m | grep 'intl'
如果此扩展功能不存在,你可以按照 安装指南 手动进行安装。如果你使用 Ubuntu,你可以直接使用以下命令安装:
sudoapt-getupdatesudoapt-getinstallphp5-intl
如果你使用的是 PHP 7,你需要添加 PPA ( ppa:ondrej/php ),升级你的系统并且安装扩展功能 Intl。
# 添加 PPAsudoadd-apt-repositoryppa:ondrej/php-7.0# 升级索引库sudoapt-getupdate# 安装扩展功能sudoapt-getinstallphp7.0-intl
消息格式化
大多数现代化应用在搭建的时候非常注意本地。有时候,这些消息是一个简单的拥有变量占位符的字符串,有时却是一个复杂的多元化的字符串。
简单信息
我们会从一个包含占位符的简单信息开始。占位符是被封闭在花括号中的字符。这里有一个示例:
var_dump( MessageFormatter::formatMessage( "en_US", "I have {0, number, integer} apples.", [ 3 ] )); // output string(16) "I have 3 apples."
传递提要给 MessageFormatter::formatMessage 的类函数如下:
- 消息的语言环境
- 消息字符串
- 占位符数据
占位符 {0, number, integer} 会键入一个数——整数作为该数据库阵列的第一个项目(看看下面列出选项的表格)我们还可以在占位符中使用命名参数。下面的示例会输出同样的结果。
var_dump( MessageFormatter::formatMessage( "en_US", "I have {number_apples, number, integer} apples.", [ 'number_apples' => 3 ] ));
不同的语言有不同的数字写法,比如阿拉伯语、印度语等等。
先前的示例指向 en_US 环境,让我们换成 ar 环境并看看有什么不同。
var_dump( MessageFormatter::formatMessage( "ar", "I have {number_apples, number, integer} apples.", [ 'number_apples' => 3 ] )); string(17) "I have ٣ apples."
让我们再换成孟加拉语情景( bn ).
var_dump( MessageFormatter::formatMessage( "bn", "I have {number_apples, number, integer} apples.", [ 'number_apples' => 3 ] )); string(18) "I have ৩ apples."
到目前为止,我们只说明了数字。现在让我们看看其他可以使用的类型。
$time = time();var_dump( MessageFormatter::formatMessage( "en_US", "Today is {0, date, full} - {0, time}", array( $time )) ); string(47) "Today is Wednesday, April 6, 2016 - 11:21:47 PM"
var_dump( MessageFormatter::formatMessage( "en_US", "duration: {0, duration}", array( $time )) ); string(23) "duration: 405,551:27:58"
我们也可以表示分数。
var_dump( MessageFormatter::formatMessage( "en_US", "I have {0, spellout} apples", array( 34 )) ); string(25) "I have thirty-four apples"
这对不同的语言环境也适用。
var_dump( MessageFormatter::formatMessage( "ar", "لدي {0, spellout} تفاحة", array( 34 )) ); string(44) "لدي أربعة و ثلاثون تفاحة"
多元化
本地化应用程序的一个重要组成部分是管理多元信息使得用户界面尽可能直观。上面苹果的示例就能说明这一点。下面是这个示例中的信息表现:
- (number_apples = 0) : 没有苹果。
- (number_apples = 1) : 一个苹果。
- (number_apples > 1) : 多个苹果。
var_dump( MessageFormatter::formatMessage( "en_US", 'I have {number_apples, plural, =0{no apples} =1{one apple} other{# apples}}', array('number_apples' => 10)) );
// number_apples = 0string(16) "I have no apples" // number_apples = 1string(16) "I have one apple" // number_apples = 10string(16) "I have 10 apples"
这种语法真的很简单直接,并且大多数包都包含这种语法。跟多细节请见 此文件 。
{data, plural, offsetValue =value{message}... other{message}}
- data :价值指数
- plural :事件参数类型
- offsetValue :可选的( offset:value )。它从值中减去偏移量。
- =value{message} :测试等价性,信息在花括号之内。我们可以重复多次 ( =0{no apples} =1{one apple} =2{two apple} )。
- other{message} :默认情况,比如在 switch - case 声明。 # 符号可用于键入 data 值。
选项
有时候,我们需要列出每一个值域的不同信息。比如下面的示例:
var_dump( MessageFormatter::formatMessage( "en_US", 'The value of {0,number} is {0, choice, 0 # between 0 and 19 | 20 # between 20 and 39 | 40 # between 40 and 59 | 60 # between 60 and 79 | 80 # between 80 and 100 | 100 < more than 100 }', array(60)) ); string(38) "The value of 60 is between 60 and 79 "
argType 在这里是为 choice 设定的,语法如下:
{value, choice, choiceStyle}
ICU 文件 的官方定义如下:
choiceStyle = numberseparatormessage ('|' numberseparatormessage)* number = normal_number | ['-'] ∞ (U+221E, infinity)normal_number = double value (unlocalizedASCIIstring) separator = less_than | less_than_or_equalless_than = '<'less_than_or_equal = '#' | ≤ (U+2264)
注意: ICU 开发者不鼓励使用选择类型。
选择项
有时我们需要选择选项UI组件。个人资料页使用这种方法根据用户的性别等等更新 UI 信息。这里有一个例子:
var_dump( MessageFormatter::formatMessage( "en_US", "{gender, select, ". "female {She has some apples} ". "male {He has some apples.}". "other {It has some apples.}". "}", array('gender' => 'female')) );string(19) "She has some apples"
模式定义如下:
{value, select, selectStyle} // selectStyleselectValue {message} (selectValue {message})*
message 提要会包括类似选项和复数的其他模式。下一个部分会解释一个被我们结合了多个模式的例子。
复杂情况
到目前为止,我们已经看过例如选择、多元化等等的简单示例。但很多情况会复杂的多。 ICU 文档 有一个很好的例子来说明这一点。为了便于理解,我们一段一段来看。
var_dump( MessageFormatter::formatMessage( "en_US", "{gender_of_host, select, ". "female {She has a party} ". "male {He has some apples.}". "other {He has some apples.}". "}", array('gender_of_host' => 'female', "num_guests" => 5, 'host' => "Hanae", 'guest' => 'Younes' )) );
这是我们之前用的一个相同的例子,不同于之前使用简单信息,我们依赖 num_guests 值定制了下(讨论的是多元化的案例)。
var_dump( MessageFormatter::formatMessage( "en_US", "{gender_of_host, select, ". "female {". "{num_guests, plural, offset:1 ". "=0 {{host} does not have a party.}". "=1 {{host} invites {guest} to her party.}". "=2 {{host} invites {guest} and one other person to her party.}". "other {{host} invites {guest} and # other people to her party.}}}". "male {He has some apples.}". "other {He has some apples.}}", array('gender_of_host' => 'female', "num_guests" => 5, 'host' => "Hanae", 'guest' => 'Younes' )) );
需要注意我们使用了 offset:1 从 num_guests 中移除一个 guest。
string(53) "Hanae invites Younes and 4 other people to her party."
下面是示例的完整段。
var_dump( MessageFormatter::formatMessage( "en_US", "{gender_of_host, select, ". "female {". "{num_guests, plural, offset:1 ". "=0 {{host} does not have a party.}". "=1 {{host} invites {guest} to her party.}". "=2 {{host} invites {guest} and one other person to her party.}". "other {{host} invites {guest} and # other people to her party.}}}". "male {". "{num_guests, plural, offset:1 ". "=0 {{host} does not have a party.}". "=1 {{host} invites {guest} to his party.}". "=2 {{host} invites {guest} and one other person to his party.}". "other {{host} invites {guest} and # other people to his party.}}}". "other {". "{num_guests, plural, offset:1 ". "=0 {{host} does not have a party.}". "=1 {{host} invites {guest} to their party.}". "=2 {{host} invites {guest} and one other person to their party.}". "other {{host} invites {guest} and # other people to their party.}}}}", array('gender_of_host' => 'female', "num_guests" => 5, 'host' => "Hanae", 'guest' => 'Younes' )) );
改变客人的数量来测试所有的信息类型:
// num_guests = 2string(55) "Hanae invites Younes and one other person to her party." // num_guests = 1string(34) "Hanae invites Younes to her party." // num_guests = 0string(28) "Hanae does not have a party."
消息解析
对于解析信息没有太多可以说;我们使用之前的模式从输出信息中来格式化额外信息。
$messageFormater = new MessageFormatter("en_US", 'I have {0, number}');var_dump( $messageFormater->parse("I have 10 apples") ); array(1) { [0]=> int(10)}
查看 文档 以获取更多关于信息解析的内容。
结论
在这篇介绍性的文章中,我们了解了使用 PHP Intel 的扩展功能来本地化我们的信息。接下来的部分会涉及格式化数字和日期,以及日历的使用。如果你对以上内容有任何疑惑,请给我们留言。

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

이 기사에서는 Laravel 웹 프레임 워크에서 알림 시스템을 탐색 할 것입니다. Laravel의 알림 시스템을 사용하면 다른 채널을 통해 사용자에게 알림을 보낼 수 있습니다. 오늘은 알림을 보낼 수있는 방법에 대해 논의합니다


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Dreamweaver Mac版
시각적 웹 개발 도구
