亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP多語言的實現

PHP多語言的實現

PHP
Smart貓小萌 2023-04-15 20:41:54
我想知道如何在 PHP 腳本中實現多種語言。我真的找不到任何方便的方法來說明如何做這樣的事情以使翻譯變得容易。我舉個例子://Output looks like this://Where are You, Mike? It is me, Rebeca! I am waiting here for 5 hours!//But in file it is some abomination like:echo 'Where are You, '.$name.'? It is me, '.$name2.'! I am waiting here for '.$time.' hours!';//Just imagine that meantime there might be different functions, included files//and other code required to create more sentences like the above to create long text...如果文件輸出這樣的文本被許多不同的變量和代碼打碎,那么語言文件應該是什么樣子的?我想到將用戶語言保存在 $_SESSION['lang'] 中,并在每個文件中包含具有正確語言的文件。但是在我嘗試這樣做之后,它確實看起來像這樣://main fileecho $txt[1].$name.$txt[2].$name2.$txt[3].$time.$txt[3];//lang file$txt[1] = 'Where are You, ';$txt[2] = '? It is me, ';$txt[3] = '! I am waiting here for ';$txt[3] = ' hours!';它看起來很可笑,不可讀,并且有很多潛在的錯誤。試想一下,如果您是只能訪問 lang 文件的翻譯人員——不可能翻譯這樣的文本,對吧?這應該/可以如何以不同的方式完成?
查看完整描述

1 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

是的,它是那樣做的,但不是像你那樣做的單個單詞或句子塊,否則它不會翻譯得很好。


通常如何處理這個問題,你定義你的模板,然后有一個你用傳遞的參數調用的函數。


請參閱: https: //www.php.net/manual/en/refs.international.php獲取 gettext 等,或查找一個庫。


例子:


<?php

$trans = [

? ? 'en' => [

? ? ? ? 'user_where_are_you_text' => 'Where are You, %s? It is me, %s! I am waiting here for %s hours!',

? ? ? ? //...

? ? ],

? ? 'fr' => [

? ? ? ? 'user_where_are_you_text' => 'Où es-tu, %s? C\'est moi, %s! J\'attends ici depuis %s heures!'

? ? ? ? //...

? ? ],

? ? //...

];


$name = 'Loz';

$name1 = 'Rasmus';

$time = 3;


function __($key, ...$arguments) {

? ? global $trans, $lang;

? ? return sprintf($trans[$lang][$key], ...$arguments);

}


//

$lang = 'en';

echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;


//

$lang = 'fr';

echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;


查看完整回答
反對 回復 2023-04-15
  • 1 回答
  • 0 關注
  • 106 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號