I am writing some code, but I got stuck at the point where I wanted to implement a language system apart from the database (maybe integrating it later). At the moment I have these lines of code in my language class:
final public function findTexts()
{
global $engine;
$file = file_get_contents('./styles/'.$engine->getStyle().''.$engine->getPage());
if(strpos($file, '%%'))
{
echo "String found";
}
}
Let me show you my other function:
final public function getText($text)
{
global $engine, $LANG;
$text = str_ireplace($text, $LANG[substr($text, 2, -2)], $text);
echo $text;
}
What I wanted to do, is check a file (which is inside a styles folder) for a string (for example %%Hi%%). Inside my language file I says Hi == Hello, so when I do the getText function it will say 'Hello'. But, I want to make it simple so you only have to type %%Hi%% inside your file, and the language class will automatically check all strings containing %% at the beginning, and %% at the end, and will replace the string inside the %% and %% with the given string inside the language file.
Hope that is enough info...
Many thanks!
You can accomplish this by using regular expressions and preg_replace_callback. See my example below:
<?php
final public function findTexts()
{
global $engine;
$file = file_get_contents('./styles/'.$engine->getStyle().''.$engine->getPage());
$language = $this;
$file = preg_replace_callback('/(%%([^%]+)%%)/',function($matches) use ($language){
$word = $matches[2];
return $language->getText($word);
},$file);
}
This method can become very slow if you have a lot of files or a lot of replacements. It's great if you are doing a very small personal website. If you're doing something a bit bigger, I highly recommend caching the result so you don't have to recompute it for every request and file.