我想用en
添加/替换网址的最后一段(无论网址参数如何)。
en
或fa
,则将en
添加为最后一段。en
或fa
,请将其替换为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
个关键字,当它们不存在时,它会失败。
答案 0 :(得分:1)
使用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;