Discuz教程网

PHP 中英文语言转换类代码

[复制链接]
authicon dly 发表于 2011-8-31 11:18:40 | 显示全部楼层 |阅读模式
起初想到制成XML文档形式,这样操作也起来很容易。只是看到说XML效率不怎样
再者就是不同的模板,可这样也有个小问题,有些词汇比如时间提示是不确定,与可能是minute ,day。也有可能复数加 s
那好吧,做成数组,可数组就得做成在php文件的变量,很难做些扩展(我所知道所认为的是这样)
最后做成txt文本文件的形式,同样也为这样的效率担心,打开文件,搜索字符串,截取字符串这些,所幸最后运行了一下,一般机子大概0.0004秒,这让我很惊奇原以为会很慢,毕竟要调用多次。
好吧,上代码
代码如下:

  1. class language
  2. {
  3. static $lanObject;
  4. public $type; // unit , dashboard , menu ,other
  5. public $lan; // language
  6. private $special; // The common in the file
  7. private function __construct()
  8. {
  9. if( isset($_GET['hl']) || isset($_POST['hl']) )
  10. {
  11. switch( isset($_GET['hl'])?$_GET['hl']:$_POST['hl'] )
  12. {
  13. case 'en':
  14. $this->lan = 'en';
  15. case 'zh':
  16. $this->lan = 'zh';
  17. case 'all':
  18. $this->lan = 'all';
  19. default:
  20. $this->error();
  21. }
  22. }
  23. else
  24. $this->lan = isset($_COOKIE['hl']) ? $_COOKIE['hl']:'zh';
  25. }
  26. public static function getObject()
  27. {
  28. if( !(self::$lanObject instanceof self) )
  29. self::$lanObject = new language();
  30. return self::$lanObject;
  31. }
  32. public function lto($key) //$key is English
  33. {
  34. if( $this->lan !== 'zh' )
  35. return $key;
  36. if( empty($this->special) ) // if the $special is null
  37. {
  38. if( isset($this->type) )
  39. $this->special = file_get_contents($this->type.'.txt');
  40. else
  41. return $key;
  42. }
  43. echo $this->search($key);
  44. }
  45. private function search($searchTozh) // PHP String
  46. {
  47. $key_start = strpos($this->special,$searchTozh);
  48. $key_end = strpos($this->special,' ',$key_start);
  49. $len_str = strlen($searchTozh);
  50. $for_sub = $key_start + $len_str + 1;
  51. return substr($this->special, $for_sub, $key_end - $for_sub);
  52. }
  53. }
复制代码

strpos(); 是找到字符串第一次出现的位置 比如 ‘wo' 在 ‘hello world' 中,返回值为 6
substr();是截取字符串的一部分  
接下来是调试时加上的代码

代码如下:

  1. $la = language::getObject();
  2. $la->type = 'unit';
  3. $la->lto('min');
  4. echo '<br/>';
  5. $la->lto('hello');
复制代码

lto(这里面要翻译的英文); 
unit.txt 文件的内容格式是
hello-你好 min-小 minute-分钟 minutes-分钟
 
$special设计为全局也是想到不止一次会调用lto() ,如果反复加载文件太浪费性能了。
$type设计为公有是考虑到加载的文件的效率问题,有的时候并不需要显示几天前这些,所以不如把这些按使用类型分开,比如有专门负责菜单翻译的menu.txt ,也有专门为操作,比如删除,收藏 翻译的txt文本。这样可以自由设定要加载的文本
语言也可以自由设定。
好吧,程序还可以改进,我没有按http请求中的客户端语言来设置$lan





上一篇:PHP 广告调用类代码(支持Flash调用)
下一篇:PHP和数据库结合的一个简单的web实例 代码分析 (PHP初学者)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 08:56

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表