网站语言切换时如何正确替换URL?避免误替换内容
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./rutargets 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).$1in 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

