如何匹配URL(字符串)的最后一段


How to match the last segment of the URL (string)?

我想添加/替换url 的最后一段(不管url参数)en .

  • 如果最后一段不是enfa,则添加en作为最后一段。
  • 如果最后一段是enfa,则将其替换为en

下面是四个例子:

:

$str = 'http://localhost:8000/search/fa?q=sth';
预期输出:

//=>    http://localhost:8000/search/en?q=sth

二:

$str = 'http://localhost:8000/search?q=sth';
预期输出:

//=>    http://localhost:8000/search/en?q=sth
三:

$str = 'http://localhost:8000/search';
预期输出:

//=>    http://localhost:8000/search/en
四:

$str = 'http://localhost:8000/search/fa';
预期输出:

//=>    http://localhost:8000/search/en

这是我到目前为止所做的尝试:

/'/(?:en|fa)(?='??)/
php版本:

preg_replace('/'/(?:en|fa)(?='??)/', '/en', Request::fullUrl())

正如你所看到的,我的模式依赖于en, fa关键字,当没有这些关键字时,它会失败。

使用parse-url、操纵路径将url拆分为各个组件,并将其编译回来:

$str = 'http://localhost:8000/search/fa?q=sth';
$parts = parse_url($str);
//play with the last part of the path:
$path = explode('/', $parts['path']);
$last = array_pop($path);
if (!in_array($last, ['en','fa'])) {        
    $path[] = $last;
}
$path[]='en';
//compile url
$result = "";
if (!empty($parts['scheme'])) {
    $result .= $parts['scheme'] . "://";
}
if (!empty($parts['host'])) {
    $result .= $parts['host'];
}
if (!empty($parts['port'])) {
    $result .= ":" . $parts['port'];
}
if (!empty($path)) {
    $result .= implode('/', $path);
}
if (!empty($parts['query'])) {
    $result .= '?' . $parts['query'];
}
echo $result;
示例