Introduction to regional language information in PHP
Operation of regional language tag information in PHP
I believe that everyone is definitely familiar with zh_CN. You will see it whether in PHP or on our web page. its figure. In fact, this is to specify which country or region our display encoding is and which language is used. There's also a lot of fun in PHP for regional language markup. Today, the Locale class we are going to learn is for operating regional language-related content. It cannot be instantiated, and all functional methods are static.
Get and set the current regional language information
The first is that we can dynamically obtain and set the corresponding regional language information.
// # echo $LANG; // en_US.UTF-8 // php.ini // intl.default_locale => no value => no value echo Locale::getDefault(), PHP_EOL; // en_US_POSIX ini_set('intl.default_locale', 'zh_CN'); echo Locale::getDefault(), PHP_EOL; // zh_CN Locale::setDefault('fr'); echo Locale::getDefault(), PHP_EOL; // fr
By default, the content of the intl.default_locale configuration in the php.ini file is obtained using the getDefault() method. If there is no configuration in php.ini, the contents of the $LANG value of the operating system will be taken, which is the en_US_POSIX output in our example above. POSIX represents the configuration from the operating system.
Use ini_set() to directly modify the ini configuration or use the setDefault() method to dynamically modify the current regional language settings.
Rules about language tags
Before continuing to study the following content, let us first learn the specifications of language tags. For most people, they may have only been exposed to tags such as en_US and zh_CN, but in fact its complete definition is very long, but when we use this abbreviation, a lot of content will be provided in the default form. The complete tagging rules are:
language-extlang-script-region-variant-extension-privateuse
Language and text type-extended language and text type-writing format-country and region-variant-extension-private
In other words, our zh_CN can be like this Write:
zh-cmn-Hans-CN-Latn-pinyin
represents: zh language type, Hans writing format is simplified Chinese, cmn Mandarin, CN country and region, Latn variant Latin alphabet, pinyin variant Pinyin.
Do you feel like something so simple suddenly becomes so big? In addition, the prefix zh- is no longer recommended. zh- is no longer the language code, but macrolang, which is the macro language. We directly use cmn, yue (Cantonese), wuu (Wu dialect), hsn (Hunan dialect, Hunan dialect) can be used as language. Therefore, the above paragraph can also be written like this:
cmn-Hans-CN-Latn-pinyin
In the previous article, when we talked about NumberFormatter, we said that we can directly obtain the output in Chinese digital format. Now what do we want the traditional result? It's very simple, just add the Hant logo writing format to Traditional Chinese.
Regarding the content of language markup rules, you can check out the Zhihu reference link at the end of the article for a more detailed introduction.
$fmt = new NumberFormatter('zh-Hant', NumberFormatter::SPELLOUT); echo $fmt->format(1234567.891234567890000), PHP_EOL; // 一百二十三萬四千五百六十七點八九一二三四五六七九
Get various information in the specified language tag rules
What can you do after learning the rules of language tags? The main function of the Locale class is to analyze and obtain these attribute information.
Get various attribute information separately
echo Locale::getDisplayLanguage('cmn-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // cmn echo Locale::getDisplayLanguage('zh-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 中文 echo Locale::getDisplayName('cmn-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // cmn(简体,中国,LATN_PINYIN) echo Locale::getDisplayName('zh-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 中文(简体,中国,LATN_PINYIN) echo Locale::getDisplayRegion('cmn-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 中国 echo Locale::getDisplayRegion('zh-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 中国 echo Locale::getDisplayScript('cmn-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 简体中文 echo Locale::getDisplayScript('zh-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // 简体中文 echo Locale::getDisplayVariant('cmn-Hans-Latn-pinyin', 'zh_CN'), PHP_EOL; // LATN_PINYIN echo Locale::getDisplayVariant('zh-Hans-CN-Latn-pinyin', 'zh_CN'), PHP_EOL; // LATN_PINYIN
We use two marking methods to test the code, and you can see the comparison of the results.
The getDisplayLanguage() method is used to obtain the displayed language information, which is the language content in the rules.
The getDisplayName() method is used to obtain the standard language name, and you can see that the content is richer.
The getDisplayRegion() method obviously obtains the country information.
getDisplayScript() obtains writing format information.
getDisplayVariant() gets variant information
Get attribute information in batches
Of course, we can also get some language-related information in batches Information.
$arr = Locale::parseLocale('zh-Hans-CN-Latn-pinyin');
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value ", PHP_EOL;
}
}
// language : zh
// script : Hans
// region : CN
// variant0 : LATN
// variant1 : PINYINUse the parseLocale() method to obtain various information in a language tag and save it in an array. The key is the tag rule name and the value is the corresponding content. See if it is the same as what we introduced above. The content is the same.
Get all variant information
As you can see from the above code, we have two variant information, which can also be obtained through a getAllVariants() method Directly obtain an array of all variant information in the language tag.
$arr = Locale::getAllVariants('zh-Hans-CN-Latn-pinyin');
var_export($arr);
echo PHP_EOL;
// array (
// 0 => 'LATN',
// 1 => 'PINYIN',
// )
获取字符集相关信息
echo Locale::canonicalize('zh-Hans-CN-Latn-pinyin'), PHP_EOL; // zh_Hans_CN_LATN_PINYIN
$keywords_arr = Locale::getKeywords('zh-cn@currency=CMY;collation=UTF-8');
if ($keywords_arr) {
foreach ($keywords_arr as $key => $value) {
echo "$key = $value", PHP_EOL;
}
}
// collation = UTF-8
// currency = CMYThe canonicalize() method is used to display language tag information in a standardized way. You can see that it changes our underscores into underlines and converts the following attributes into uppercase. This is canonicalization. Writing method. However, for our applications and web pages, underscores and upper and lower case are supported. Of course, it is best for everyone to define it according to the standard writing method.
getKeywords() is used to obtain language-related information attributes from the @ symbol, such as the zh-cn we defined, and then defined its currency as CMY and character set as UTF-8, directly through getKeywords () to get an array of currency and character set attributes.
Matching judgment language tag information
For language tags, we can judge whether the two given tags match each other, such as:
echo (Locale::filterMatches('cmn-CN', 'zh-CN', false)) ? "Matches" : "Does not match", PHP_EOL; echo (Locale::filterMatches('zh-CN-Latn', 'zh-CN', false)) ? "Matches" : "Does not match", PHP_EOL;
Of course, we can also use another lookup() method to determine which of a given series of language tags is closest to the specified tag.
$arr = [
'zh-hans',
'zh-hant',
'zh',
'zh-cn',
];
echo Locale::lookup($arr, 'zh-Hans-CN-Latn-pinyin', true, 'en_US'), PHP_EOL; // zh_hansGenerate a standard rule language tag
既然能够获取各类语言标记的属性信息,那么我们能不能生成一个标准的语言标记内容呢?
$arr = [
'language' => 'en',
'script' => 'Hans',
'region' => 'CN',
'variant2' => 'rozaj',
'variant1' => 'nedis',
'private1' => 'prv1',
'private2' => 'prv2',
];
echo Locale::composeLocale($arr), PHP_EOL; // en_Hans_CN_nedis_rozaj_x_prv1_prv2没错,composeLocale() 方法根据一个数组格式的内容,就可以生成一个完整标准的语言标记格式内容。当然,这个测试代码是乱写的,相当于是一个 en_CN 的标记,正常不会这么写的。
acceptFromHttp 从请求头中读取语言信息
另外,Locale 类中还提供了一个从 header 头中的 Accept Language 中获取客户浏览器语言信息的方法。
// Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); echo Locale::acceptFromHttp('en_US'), PHP_EOL; // en_US echo Locale::acceptFromHttp('en_AU'), PHP_EOL; // en_AU echo Locale::acceptFromHttp('zh_CN'), PHP_EOL; // zh echo Locale::acceptFromHttp('zh_TW'), PHP_EOL; // zh
不过从测试的结果来说,其实它只需要一个字符串参数就可以了,所以我们在命令行也可以测试它。需要注意的是,对于中文来说,它不能返回区域信息,只能返回 language 信息。
推荐学习:《PHP视频教程》
总结
这个 Locale 类相关的内容其实在笔者日常的开发中基本没怎么接触过,但相信不少做跨境项目的同学会多少对它们会有一些了解。只能说业务接触不到,那就只能先简单地学习一下看看了,同样地,以后大家遇到相关的业务需求时,别忘了它们的存在哦!
测试代码: https://github.com/zhangyue0503/dev-blog/blob/master/php/202011/source/5.PHP中针对区域语言标记信息的操作.php 参考文档: https://www.php.net/manual/zh/class.locale.php https://www.zhihu.com/question/20797118/answer/63480740
The above is the detailed content of Introduction to regional language information in PHP. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
What are public, private, and protected in php
Aug 24, 2025 am 03:29 AM
Public members can be accessed at will; 2. Private members can only be accessed within the class; 3. Protected members can be accessed in classes and subclasses; 4. Rational use can improve code security and maintainability.
How to execute an UPDATE query in php
Aug 24, 2025 am 05:04 AM
Using MySQLi object-oriented method: establish a connection, preprocess UPDATE statements, bind parameters, execute and check the results, and finally close the resource. 2. Using MySQLi procedure method: connect to the database through functions, prepare statements, bind parameters, perform updates, and close the connection after processing errors. 3. Use PDO: Connect to the database through PDO, set exception mode, pre-process SQL, bind parameters, perform updates, use try-catch to handle exceptions, and finally release resources. Always use preprocessing statements to prevent SQL injection, verify user input, and close connections in time.
How to use cURL in php
Aug 24, 2025 am 08:32 AM
cURLinPHPenablessendingHTTPrequests,fetchingAPIdata,anduploadingfiles.Initializewithcurl_init(),setoptionslikeCURLOPT_URLandCURLOPT_RETURNTRANSFER,useCURLOPT_POSTforPOSTrequests,sendJSONwithproperheaders,handleerrorsviacurl_errno()andHTTPcodeswithcur
How to read a CSV file in PHP?
Aug 29, 2025 am 08:06 AM
ToreadaCSVfileinPHP,usefopen()toopenthefile,fgetcsv()inalooptoreadeachrowasanarray,andfclose()tocloseit;handleheaderswithaseparatefgetcsv()callandspecifydelimitersasneeded,ensuringproperfilepathsandUTF-8encodingforspecialcharacters.
How to use AJAX with php
Aug 29, 2025 am 08:58 AM
AJAXwithPHPenablesdynamicwebappsbysendingasynchronousrequestswithoutpagereloads.1.CreateHTMLwithJavaScriptusingfetch()tosenddata.2.BuildaPHPscripttoprocessPOSTdataandreturnresponses.3.UseJSONforcomplexdatahandling.4.Alwayssanitizeinputsanddebugviabro
What is the difference between isset and empty in php
Aug 27, 2025 am 08:38 AM
isset()checksifavariableexistsandisnotnull,returningtrueevenforzero,false,oremptystringvalues;2.empty()checksifavariableisnull,false,0,"0","",orundefined,returningtrueforthese"falsy"values;3.isset()returnsfalsefornon-exi
Edit bookmarks in chrome
Aug 27, 2025 am 12:03 AM
Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.
How to configure SMTP for sending mail in php
Aug 27, 2025 am 08:08 AM
Answer: Using the PHPMailer library to configure the SMTP server can enable sending mails through SMTP in PHP applications. PHPMailer needs to be installed, set up SMTP host, port, encryption method and authentication credentials of Gmail, write code to set sender, recipient, topic and content, enable 2FA and use application password to ensure that the server allows SMTP connection, and finally call the send method to send email.


