Search code examples
phparraysstringtranslate

Check if piece of string exists inside array


I am using this function to translate stuff:

function t($string)
{
    global $_ACTIVE_LANGUAGE;
    if(is_array($_ACTIVE_LANGUAGE) && array_key_exists($string,$_ACTIVE_LANGUAGE) )
    {
        return (!empty($_ACTIVE_LANGUAGE[$string])) ? $_ACTIVE_LANGUAGE[$string] : $string; 
    } else {
        return $string;
    }
}

It works well, I put t('hola') and if there's the english file with the array 'hola' => 'hello' it translates it.

However, now I want to be able to translate strings which can contain more text than just the string, like this example:

$string1 = 'download-file-justin-bieber-awesome-voice.html';
$string2 = 'view-file-rihanna-very-sexy.html';
$string3 = 'mostseen12345.html';
$string4 = 'incredible:stuff-and:real-things.html';

$array = array
(
    'download-file' => 'descargar-archivo',
    'view-file' => 'ver-archivo',
    'mostseen' => 'masvistos',
    'incredible:stuff' = 'cosas:increibles'
}

I want the script to be able to translate the parts in the keys of the array in the given strings. Is this possible at all?


Solution

  • You could check out str_replace() at the php-manual.

    $from = array('download-file','view-file','mostseen','incredible:stuff');
    $to   = array('descargar-archivo','ver-archivo','masvistos','cosas:increibles');
    
    $translated_string = str_replace($from,$to,$original_string);