Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

regex - How to get the language value from $_SERVER['HTTP_ACCEPT_LANGUAGE'] using PHP?

<?php
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo $language;
?>

When I use Firefox to test this block of code, I get en-us,en;q=0.7,ja;q=0.3,

when I use IE to test the block of code, I get zh-cn.

Is the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] a string? How to determine whether the preferred language is Chinese or Japanese? How can I write a regular expression to get the language from the value of $_SERVER['HTTP_ACCEPT_LANGUAGE']?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] is a string -- see $_SERVER.

Its content is sent by the browser -- which explains why you get different results depending on the browser you are using : most likely, your Firefox is configured to request pages in english (high priority) or japanese (low priority), while your IE is configured to request pages in chinese.

This is because that HTTP header can contain :

  • a list of languages
  • optionnaly, with region codes
  • with associated priorities.

The idea being that the server should respond, using the language that suits "the best" what's requested by the user.


About parsing that header, this blog-post might be a interesting read : Parse Accept-Language to detect a user's language

There is a portion of code proposed to parse that HTTP header -- and it generates an array that looks like this (quoting) :

Array
(
    [en-ca] => 1
    [en] => 0.8
    [en-us] => 0.6
    [de-de] => 0.4
    [de] => 0.2
)

Which is an array of languages, sorted by priority, in descending order -- which is probably what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...