Skip to content
Advertisement

Multilingual PHP Inline Replacement in HTML ([en]…[/en] etc.)

I am a coding beginner and have my PHP/HTML web project in German. Now I want to make it available in English in the easiest way. I don’t want to add other languages in the future, so I want to try it in the easiest (and maybe not the most proper) way.

I have PHP files with HTML content and the selected language available in a var, i.e.:

<?php
$lang = "en";
?> 

<h1>Title in German</h1>

So all the German words are inline HTML. My idea was to create something like:

<h1>[de]Title in German[/de][en]Title in English[/en]</h1>

But I have no idea how to replace it on every load in a smart way. So it is more a topic on “live replacement”.

Working with constants in an external language file is of course also an option, like all the other options to make a multilingual site I found on Stackoverflow.

But maybe there is a “quick and dirty” possibility option like the one I mentioned?

Thank you for every hint!

Advertisement

Answer

You could try and do this will almost only HTML and CSS. You would need to add this at the top of your page:

<?php

$pageLanguage = "en";

function getLanguageStyle($showLanguage)
{ 
   global $pageLanguage;
   $display = ($showLanguage == $pageLanguage ? 'inline' : 'none');
   return "  span.$showLanguage { display: $display }n";         
}

echo "<style>n".
     getLanguageStyle('en').
     getLanguageStyle('de').
     "</style>n";

?> 

It sets up a style for each language, which you can then use like this:

<h1><span class="de">Title in German</span><span class="en">Title in English</span></h1>

The advantage here is that you don’t need to mix HTML and PHP. This is not a normal way of doing this, but it will work. On very complex pages, where these styles are applied after the first render, this might not be pleasant for your visitors.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement