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

如何在CI3中修剪URI?从$_SERVER["REQUEST_URI"]提取指定路径段

从$_SERVER["REQUEST_URI"]中提取指定URL分段

针对你的需求(从/vobot-cms/perdana/Perdana/tambahData提取/Perdana),可以用以下几种简单方法实现:

方法1:字符串分割法

通过explode()将URL按/拆分,提取目标分段后拼接前缀:

$requestUri = $_SERVER["REQUEST_URI"];
// 移除首尾的/,避免分割出空元素
$segments = explode('/', trim($requestUri, '/'));

// 确保目标分段存在,避免数组越界
$targetPath = '';
if (isset($segments[2])) {
    $targetPath = '/' . $segments[2];
}

echo $targetPath; // 输出:/Perdana

解释:原URL拆分后得到数组["vobot-cms", "perdana", "Perdana", "tambahData"],$segments[2]就是我们需要的Perdana,加上前缀/即可。

方法2:正则表达式匹配法

用正则直接捕获目标分段,适合URL结构固定的场景:

$requestUri = $_SERVER["REQUEST_URI"];
$targetPath = '';

// 匹配前两个分段后的目标内容
if (preg_match('#/[^/]+/[^/]+/([^/]+)#', $requestUri, $matches)) {
    $targetPath = '/' . $matches[1];
}

echo $targetPath; // 输出:/Perdana

解释:正则#/[^/]+/[^/]+/([^/]+)#会匹配/开头,跳过前两个分段(vobot-cms和perdana),捕获第三个分段的内容(Perdana),最后拼接前缀/。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:50:16