Table of Contents
Get and set the current regional language information" >Get and set the current regional language information
Rules about language tags" >Rules about language tags
Get various information in the specified language tag rules" >Get various information in the specified language tag rules
Acquire various attribute information separately
Get attribute information in batches
Get all variant information
Get character set related information
匹配判断语言标记信息" >匹配判断语言标记信息
生成一个标准规则的语言标记" >生成一个标准规则的语言标记
acceptFromHttp 从请求头中读取语言信息" >acceptFromHttp 从请求头中读取语言信息
总结" >总结
Home Backend Development PHP Problem How to operate regional language markup information in PHP

How to operate regional language markup information in PHP

Jul 01, 2021 pm 03:26 PM
php

I believe that everyone is definitely familiar with zh_CN. Whether it is in PHP or on our web page, you will see it. In fact, this is to specify which country or region our display encoding is and which language is used. What we are going to learn today is the Locale class that operates regional language-related content.

How to operate regional language markup information in PHP

I believe that everyone is definitely familiar with zh_CN. Whether it is in PHP or on our web page, you will see it. 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
Copy after login

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 marking rule is:

language-extlang-script-region-variant-extension-privateuse
语言文字种类-扩展语言文字种类-书写格式-国家和地区-变体-扩展-私有
Copy after login

In other words, our zh_CN can be written like this:

zh-cmn-Hans-CN-Latn-pinyin
Copy after login

represents: zh language type, Hans writing format is Simplified Chinese, cmn Mandarin, CN countries and regions, Latn variant Latin letters, 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
Copy after login

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; 
// 一百二十三萬四千五百六十七點八九一二三四五六七九
Copy after login

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.

Acquire 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
Copy after login

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 rule.

  • 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() gets the writing format information.

  • getDisplayVariant() gets the variant information

Get attribute information in batches

Of course, we can also batch it to obtain some language-related 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 : PINYIN
Copy after login

Use 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 can be seen from the above code, we have two variant information. This can also be directly obtained through a getAllVariants() method in the language tag. Array of all variant information.

$arr = Locale::getAllVariants('zh-Hans-CN-Latn-pinyin');
var_export($arr);
echo PHP_EOL;
//  array (
//     0 => 'LATN',
//     1 => 'PINYIN',
//   )
Copy after login
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 = CMY
Copy after login

The canonicalize() method is used to display language mark information in a standardized way. You can see that it changes our underscore into an underline and changes the following Various attributes are converted to uppercase, which is the standardized way of writing. 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.

匹配判断语言标记信息

对于语言标记来说,我们可以判断给定的两个标记之间是否相互匹配,比如:

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;
Copy after login

当然,我们也可以使用另一个 lookup() 方法来确定给定的一系列语言标记哪个与指定的标记最接近。

$arr = [
    'zh-hans',
    'zh-hant',
    'zh',
    'zh-cn',
];
echo Locale::lookup($arr, 'zh-Hans-CN-Latn-pinyin', true, 'en_US'), PHP_EOL; // zh_hans
Copy after login

生成一个标准规则的语言标记

既然能够获取各类语言标记的属性信息,那么我们能不能生成一个标准的语言标记内容呢?

$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
Copy after login

没错,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
Copy after login

不过从测试的结果来说,其实它只需要一个字符串参数就可以了,所以我们在命令行也可以测试它。需要注意的是,对于中文来说,它不能返回区域信息,只能返回 language 信息。

总结

这个 Locale 类相关的内容其实在笔者日常的开发中基本没怎么接触过,但相信不少做跨境项目的同学应该多少对它们会有一些了解。只能说业务接触不到,那就只能先简单地学习一下看看了,同样地,以后大家遇到相关的业务需求时,别忘了它们的存在哦!

推荐学习:php视频教程

The above is the detailed content of How to operate regional language markup information in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles