Question

I just need to make a simple string translation (url) with an array of keys and their translations.

Trying like this:

function ruta_iso( $ruta ) {
    $slugs = array(
        'noticia' => array(
            'es' => 'noticia',
            'en' => 'post'
        ),
        'pregunta' => array(
            'es' => 'pregunta',
            'en' => 'question'
        ),
        'consejo' => array(
            'es' => 'consejo',
            'en' => 'tip'
        ),
        'noticias' => array(
            'es' => 'noticias',
            'en' => 'news'
        )
    );


    $idioma_defecto = 'es';
    $idioma = 'en' ;

    if ( ($idioma != $idioma_defecto) && ($ruta == '/') ) {
        return "/$idioma";
    } else if( $idioma !=  $idioma_defecto ){
        foreach($slugs as $key => $slug){
            if ( ( strpos("/$key/", $ruta ) === false ) ){
            }else {
                $ruta = str_replace( "/$key/", '/'.$slug[$idioma].'/' , $ruta );

            }
        }
        $ruta = "/$idioma$ruta"; 
    } else {

    }
    return $ruta;
}

echo '-------Ruta Iso '.ruta_iso('/noticias/'); /* Works! */

echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/'); /* Nope.. */

Can be tested here:

http://codepad.org/3w3Vmncg

It seems to Do the job for one slug, but not if there are more than one, even:

echo ' -------Ruta Iso '.ruta_iso('/noticias/blabla/'); /* Nope.. */

So I am not sure how to try, I mean, I am not breaking the foreach, why is not every string checked?

Any toghts?

Was it helpful?

Solution

You can also try to do so:

function ruta_iso( $ruta = '') {
    $slugs = array(
        'noticia' => array(
            'es' => 'noticia',
            'en' => 'post'
        ),
        'pregunta' => array(
            'es' => 'pregunta',
            'en' => 'question'
        ),
        'consejo' => array(
            'es' => 'consejo',
            'en' => 'tip'
        ),
        'noticias' => array(
            'es' => 'noticias',
            'en' => 'news'
        )
    );

    $idioma_defecto = 'es';
    $idioma = 'en' ;

    foreach( explode('/',  $ruta) as $data){
    if( !empty($data) ){

        if( array_key_exists($data, $slugs)){
            $result[] = $slugs[$data][$idioma];
        }else{
            $result[] = $data;
        }
    }
}
    $result = '/'.$idioma.'/'.implode('/', $result).'/';

    return $result;
}

echo '-------Ruta Iso '.ruta_iso('/noticias/');

echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/');

echo '-------Ruta Iso '.ruta_iso('/noticias/noticia/the-new');

Result:

-------Ruta Iso /en/news/ -------Ruta Iso /en/news/post/
-------Ruta Iso /en/news/post/the-new/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top