【问题标题】:Good method to do text with links in gettext?用gettext中的链接做文本的好方法?
【发布时间】:2009-09-28 00:43:40
【问题描述】:

我目前正在使用 PHP 使用 gettext 进行国际化。我想知道这个例子是否有什么好的方法:

By using this website, you accept the <a href="<?php print($dir); ?>/tos/">Terms of Use</a>.

对于 en_US,这句话将遵循这样的格式。但是,在另一种语言中,“使用条款”链接可能位于句子的开头。有没有一种优雅的方式来做到这一点?感谢您的宝贵时间。

【问题讨论】:

    标签: php gettext


    【解决方案1】:

    为了简单的国际化,我将简单地为每种语言创建一个数组,包含正确的文件,然后访问该数组,而不是做你正在做的事情。

    en.php:

    $text = array(
         'footer' => 'By using this website, you accept the <a href="' . $dir . '/tos/">Terms of Use</a>.',
         'welcome' => 'Welcome to our website!'
    );
    

    index.php:

    $langdir = '/path/to/languages';
    $lang = ( $_GET['lang'] ) ? $langdir . '/' . $_GET['lang'] . '.php' : $langdir . '/en.php';
    if( dirname($lang) != $langdir || !require_once( $lang ) )
         exit('Language does not exist');
    
    echo '<p class="footer">' . $text['footer'] . '</p>';
    

    dirname() 调用很关键;否则用户可以未经审查地访问您文件系统上的任何 php 文件。

    【讨论】:

    • 提出这个问题的人已经在使用 gettext,他不打算切换到另一个系统,尤其是劣质系统。在让翻译人员编辑 PHP 文件时,使用充满翻译和安全问题的大型 PHP 文件存在许多缺陷。其中,格式错误的字符串可能会终止您的脚本,或者更具体地说,在翻译包含变量的情况下,您的系统需要在包含文件之前知道所有可能的变量。 gettext 是一种行之有效的方法,无需重新发明六角轮。
    【解决方案2】:

    我会这样做。要翻译的短语是

    By using this website, you accept the <a>Terms of Use</a>.
    

    然后我会在短语本地化后替换链接,例如

    $str = _('By using this website, you accept the <a>Terms of Use</a>.');
    $str = preg_replace('#<a>(.*?)</a>#', '<a href="' . $dir . '/tos/">$1</a>', $str);
    

    当然,您可以将&lt;a&gt;&lt;/a&gt; 替换为对您和您的翻译人员有意义的任何内容。想一想,因为您必须转义输出以防止翻译者弄乱您的 HTML(有意或无意),我可能会选择类似

    $str = htmlspecialchars(_('By using this website, you accept the [tos_link]Terms of Use[/tos_link].'));
    $str = preg_replace('#\\[tos_link\\](.*?)\\[/tos_link\\]#', '<a href="' . $dir . '/tos/">$1</a>', $str);
    

    【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 2015-11-27
    • 2014-06-13
    • 2017-11-19
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多