题
我使用PHP目前正在做与gettext的国际化。我想知道是否有这个例子的任何良好的方法:
By using this website, you accept the <a href="<?php print($dir); ?>/tos/">Terms of Use</a>.
有关EN_US,这句话将遵循这样的格式。然而,在另一种语言,链接“使用条款”可能是在句子的开头。有一种优雅的方式来做到这一点?感谢您的时间。
解决方案
下面就是我会做。要翻译的短语将是
By using this website, you accept the <a>Terms of Use</a>.
然后,我取代链路短语被定位后,e.g。
$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);
当然,你可以用任何有意义的你和你的翻译代替<a>
和</a>
。试想想它,因为你必须逃脱你的输出,以防止译者与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);
其他提示
对于简单的国际,我会简单地创建每种语言的阵列,包括正确的文件,并访问数组,而不是你在做什么。
<强> 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文件未经审查访问你的文件系统。
不隶属于 StackOverflow