You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网站语言切换时如何正确替换URL?避免误替换内容

Fixing Accidental Replacement of Language Code in URL Segments

The issue here is that str_replace does a literal substring replacement, so it will match "/ru" anywhere in the URL path—even when it’s part of another segment like "/rumanya-test". To avoid this, we need to target only the initial language segment (the "/ru" at the start of the URL) using a regular expression instead.

Here’s how to adjust your code:

Instead of using str_replace, switch to preg_replace with a regex that matches the language code only when it’s at the beginning of the path, followed by either a slash (to start the next segment) or the end of the string (for the root language page):

if ($lang == 'ru') {
    $ru_href = 'javascript:void(0);';
    $en_href = preg_replace('#^/ru(/|$)#', '/en$1', $_SERVER['REQUEST_URI']);
    $md_href = preg_replace('#^/ru(/|$)#', '/md$1', $_SERVER['REQUEST_URI']);
    $logo_href = '/ru/';
} elseif ($lang == 'en') {
    $ru_href = preg_replace('#^/en(/|$)#', '/ru$1', $_SERVER['REQUEST_URI']);
    $en_href = 'javascript:void(0);';
    $md_href = preg_replace('#^/en(/|$)#', '/md$1', $_SERVER['REQUEST_URI']);
    $logo_href = '/en/';
} elseif ($lang == 'md') {
    $ru_href = preg_replace('#^/md(/|$)#', '/ru$1', $_SERVER['REQUEST_URI']);
    $en_href = preg_replace('#^/md(/|$)#', '/en$1', $_SERVER['REQUEST_URI']);
    $md_href = 'javascript:void(0);';
    $logo_href = '/md/';
}

How the regex works:

  • #^/ru(/|$)#:
    • ^ ensures we’re matching at the start of the URL string.
    • /ru targets the literal language segment.
    • (/|$) matches either a trailing slash (to handle URLs like /ru/page) or the end of the string (for the root URL /ru).
    • $1 in the replacement inserts whatever was captured in the parentheses (either the slash or nothing), so the URL structure stays intact.

This way, only the initial language code is replaced, and segments like "/rumanya-test" remain unchanged—no extra slashes needed for the language identifier.

内容的提问来源于stack exchange,提问作者GodmanT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:36:38