PHP如何替换URL中的特定字符串


PHP How to replace specific string from an URL

我正在PHP中构建一个多语言网络,我有语言变化的类,我可以通过设置$_SESSION或只是通过改变url中的lang值来做到这一点,我正在为apache重写mod,所以这就是我的url看起来像:

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

我有一个函数,在整个网站上显示一个上方栏,在该栏中我有语言更改的标志。

我使用这个类来改变语言:

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;
        }
    }
}

我用下面的代码使用这个类:

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

并像这样设置语言:

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'];
}

现在我遇到的问题是,当我试图改变我所处页面的语言时,我的意思是,如果我位于www.server.com并且没有其他任何东西,我需要将/es或/en放在末尾以更改语言,但如果我在www.server.com/es/something/else/to/do,我需要特别更改/es参数。

我有一个功能,以获得当前的url重定向时被记录或注册。

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

我试图改变函数中的lang值,但没有成功,

非常感谢您的帮助

我有一个简单的解决方案。我不知道这是不是你想用的:

 // 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;

您可能需要在$pos上加减1来获得正确的返回值,如下所示:

 $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

请调整和测试这个,它只是在行动的概念,我还没有测试这个片段-

最后我通过修改getUrl函数得到了它:

function getUrl($newlang) {
    $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
    $url .= $_SERVER["REQUEST_URI"];
    $substr = substr($url,27,3);
    $base = substr($url,0,28);
    $resto = substr($url,31,1000);
    $newUrl = $base.$newlang."/".$resto;
    return $newUrl;
}

并像这样调用函数getUrl("en")或getUrl("es");

也许这对别人有用