dth2331 2014-08-19 16:57
浏览 64

PHP如何从URL替换特定字符串

I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:

http://www.server.com/en/something/else/to/do

I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.

I use this class to change Language:

class IDIOMAS {

    private $UserLng;
    private $langSelected;
    public $lang = array();


    public function __construct($userLanguage){

        $this->UserLng = $userLanguage; 
    }

    public function userLanguage(){

        switch($this->UserLng){

            case "en":
                $lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';

                // Menu

                $lang['MENU_LOGIN'] = 'Login';
                $lang['MENU_SIGNUP'] = 'Sign up';
                $lang['MENU_LOGOUT'] = 'Logout';
                $lang['MENU_SEARCH'] = 'Search';

                //Suscripciones
                $lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
                $lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
                $lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
                $lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
                $lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
                $lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
                $lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
                $lang['SUBSCRIBE_SEND'] = 'SEND';

                //LOGIN
                $lang['LOGIN_TITLE'] = 'Please Login to your account';
                $lang['LOGIN_USER'] = 'User';
                $lang['LOGIN_PASSWORD'] = 'Password';
                $lang['LOGIN_ERROR'] = '¡User and/or password invalid!';

                //REGISTER
                $lang['REGISTER_NAME'] = 'Please write your name';
                $lang['REGISTER_LAST_NAME'] = 'Please write your last name';
                $lang['REGISTER_EMAIL'] = 'Write your E-mail';
                $lang['REGISTER_CITY'] = 'Enter your City name';
                $lang['REGISTER_COUNTRY'] = '¿Where are you from?';
                $lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
                $lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';


                return $lang;
                break;

            case "es":
                $lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';

                // Menu

                $lang['MENU_LOGIN'] = 'Entrar';
                $lang['MENU_SIGNUP'] = 'Registrarse';
                $lang['MENU_LOGOUT'] = 'Salir';
                $lang['MENU_SEARCH'] = 'Buscar';

                //Suscripciones
                $lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
                $lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
                $lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
                $lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
                $lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
                $lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
                $lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
                $lang['SUBSCRIBE_SEND'] = 'Enviar';

                //LOGIN
                $lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
                $lang['LOGIN_USER'] = 'Usuario';
                $lang['LOGIN_PASSWORD'] = 'Clave';
                $lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';

                //REGISTRO
                $lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
                $lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
                $lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
                $lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
                $lang['REGISTRO_PAIS'] = '¿De donde eres?';
                $lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
                $lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';

                return $lang;
                break;

        }
    }
}

I use this class with this code:

$language = new IDIOMAS($lang);
$langArray = array();
$langArray =  $language->userLanguage();

And set the language like this:

if (!isset($_SESSION['idioma'])){
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $_SESSION['idioma'] = $lang;
}else{
    $lang = $_SESSION['idioma'];
}

if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
    $_SESSION['idioma'] = $_GET['lang'];
    $lang = $_SESSION['idioma'];
}

Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.

I have a function to get the current url for redirections when being logged or register.

function getUrl() {
  $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
  $url .= $_SERVER["REQUEST_URI"];
  return $url;
}

I was trying to change the lang value inside that function with no success,

Really appreciate any help

  • 写回答

2条回答 默认 最新

  • douxuanma4357 2014-08-19 18:21
    关注

    Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:

     // Find the first forward slash location
     $pos1 = strpos($url,'/'); // The whole URL
     // You only need this next line if your language codes are different sizes
     // If they are always 2 then can alter the code to not use it
     $pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
    
     $base = substr($url,0,$pos1); // Get domain name half
     $end = substr($url,$pos2); // Get everything after language area
    
     // Now from the function return the result
     $val = $base.'/'.$newlang.'/'.$end;
     return $val;
    

    You may need to add or subtract 1 on the $pos to get the right values returned, like so:

     $pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
     $base = substr($url,0,$pos1-1); // In case its returning the slash
     $end = substr($url,$pos2+1); // In case its return the slash
    

    Please tweak and test this, it is only the concept in action, I have not tested this snip-it.

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮