tags:

views:

59

answers:

2

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.

A: 

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);
Josh Davis
Clever regex, but...now you have two problems.http://www.codinghorror.com/blog/archives/001016.html
cpharmston
i read the article... what are the two problems? :p
Axsuul
i applied this and it worked great! thanks
Axsuul
+1  A: 

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.

cpharmston
Made a few security/bulletproofness updates.
cpharmston
The person who asked that question is already using gettext, he's not looking to switch to another system, especially an inferior one. There are many flaws in using big PHP files filled with translations and security issues in letting translators edit PHP files. Among others, malformed strings can terminate your script or more specifically in case of translations containing variables, your system requires all possible variables to be known before including the file. gettext is a proven method, no need to reinvent an hexagonal wheel.
Josh Davis