下面是實例代碼
html' target='_blank'>class language { static $lanObject; public $type; // unit , dashboard , menu ,other public $lan; // language private $special; // The common in the file private function construct() { if( isset($_GET['hl']) || isset($_POST['hl']) ) { switch( isset($_GET['hl'])?$_GET['hl']:$_POST['hl'] ) { case 'en': $this->lan = 'en'; case 'zh': $this->lan = 'zh'; case 'all': $this->lan = 'all'; default: $this->error(); } } else $this->lan = isset($_COOKIE['hl']) ? $_COOKIE['hl']:'zh'; } public static function getObject() { if( !(self::$lanObject instanceof self) ) self::$lanObject = new language(); return self::$lanObject; } public function lto($key) //$key is English { if( $this->lan !== 'zh' ) return $key; if( empty($this->special) ) // if the $special is null { if( isset($this->type) ) $this->special = file_get_contents($this->type.'.txt'); else return $key; } echo $this->search($key); } private function search($searchTozh) // PHP String { $key_start = strpos($this->special,$searchTozh); $key_end = strpos($this->special,' ',$key_start); $len_str = strlen($searchTozh); $for_sub = $key_start + $len_str + 1; return substr($this->special, $for_sub, $key_end - $for_sub); } }
strpos(); 是找到字符串第一次出現的位置 比如 ‘wo' 在 ‘hello world' 中,返回值為 6
substr();是截取字符串的一部分
接下來是調試時加上的代碼
$la = language::getObject(); $la->type = 'unit'; $la->lto('min'); echo '<br/>'; $la->lto('hello');
lto(這里面要翻譯的英文);
unit.txt 文件的內容格式是
hello-你好 min-小 minute-分鐘 minutes-分鐘
$special設計為全局也是想到不止一次會調用lto() ,如果反復加載文件太浪費性能了。
$type設計為公有是考慮到加載的文件的效率問題,有的時候并不需要顯示幾天前這些,所以不如把這些按使用類型分開,比如有專門負責菜單翻譯的menu.txt ,也有專門為操作,比如刪除,收藏 翻譯的txt文本。這樣可以自由設定要加載的文本
語言也可以自由設定。
以上就是php 中英文語言轉換類詳解的詳細內容,更多請關注 其它相關文章!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答