Good method to do text with links in gettext?
Question
I'm currently doing internationalization with gettext using PHP. I was wondering if there were any good methods for this example:
By using this website, you accept the <a href="<?php print($dir); ?>/tos/">Terms of Use</a>.
For en_US, this sentence would follow such a format. However, in another language, the link "Terms of Use" could be at the beginning of the sentence. Is there an elegant way to do this? Thanks for your time.
Solution
Here's how I'd do it. The phrase to be translated would be
By using this website, you accept the <a>Terms of Use</a>.
Then I'd replace the link after the phrase is localised, 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);
Of course you can replace <a>
and </a>
with whatever makes sense to you and your translators. Come to think of it, since you have to escape your output to prevent translators from messing up with your HTML (intentionally or not) I'd probably go with something like
$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);
OTHER TIPS
For simple internationalization, I'll simply create an array per language, include the proper file, and access that array rather than do what you are doing.
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>';
The dirname()
call is critical; otherwise users get unvetted access to any php file on your filesystem.