PHP - 替换链接中的子文件夹(为了更改语言)


PHP - Replace subfolder in link (in order to change language)

这是我在这个论坛上的第一篇文章,所以请原谅我的任何无意错误。

所以,让我试着解释一下我的问题是什么:

我有一个两种语言的网站,其文件夹结构如下:

我的网站/俄罗斯(俄语)和mywebsite/zh (简体中文)

当我在俄语版本的网站上时,所有类别的链接如下所示:

subdomain.domain.com/ru/clients/myclient,subdomain.domain.com/ru/services/myservice等

当我在网站的英文版上时,链接看起来是一样的,唯一的区别是/en/子文件夹而不是/ru/子文件夹:

subdomain.domain.com/en/clients/myclient,subdomain.domain.com/en/services/myservice

我想做的是在网站的标题中有两个链接,一个用于英语,一个用于俄语,这些链接应该自动将语言切换到当前页面的英语/俄语版本。

所以,如果我在 subdomain.domain.com/ru/services/myservice 上并单击英文链接,我想被重定向到 subdomain.domain.com/en/services/myservice或者,如果我在

因此,如果我在 subdomain.domain.com/ru/clients/myclient 上并单击英文链接,我希望被重定向到 subdomain.domain.com/en/clients/myclient

所以基本上,我需要一个 php 脚本(或 javascript,如果它更容易的话)来保留现有链接并将/ru/部分更改为/en/,反之亦然。

我尝试在网上搜索解决方案,但找不到真正适合我的解决方案。谢谢!

使用绝对链接,您可以执行以下操作:

// REQUEST_URI contains your current URI like '/en/services/myservice'
// split this URI by '/'
$uriParts = explode('/', $_SERVER['REQUEST_URI']);
// get all values after 'en'
$uriPartsWithoutLang = array_slice($uriParts, 2);
// prefix the new URI with 'ru' and 
// concatinate the remaining array values with '/' again
$newUri = '/ru/' . implode('/', $uriPartsWithoutLang);
// print out the link
echo '<a href="' , $newUri , '">Russia</a>';

你可以为此str_replace函数

http://php.net/manual/en/function.str-replace.php

 $url = "subdomain.domain.com/ru/clients/myclient";
 $newurl =  str_replace("ru","en",$url);