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

如何用PHP获取URL最后一个斜杠前的部分?

当然有可行的方案啦!根据你给出的URL结构,我整理了几种不同场景下的实现方法,你可以根据自己使用的工具或编程语言来选择:

方案1:Python 实现

在Python里,你可以借助标准库的urllib.parse来解析URL,稳妥处理路径部分:

from urllib.parse import urlparse

url = "https://example.com/something/this-is-my-part/10448887"
parsed_url = urlparse(url)
# 拆分路径并过滤空字符串
path_segments = [seg for seg in parsed_url.path.split('/') if seg]

# 如果你确定目标是第三个路径段(从0开始索引)
target_part = path_segments[2]
# 或者更灵活:如果目标永远在最后的数字ID之前,取倒数第二个段
# target_part = path_segments[-2]

print(target_part)  # 输出: this-is-my-part
方案2:JavaScript/Node.js 实现

浏览器或Node.js环境下,可以用原生URL对象来处理:

const url = new URL("https://example.com/something/this-is-my-part/10448887");
const pathSegments = url.pathname.split('/').filter(seg => seg);

// 同样可以选固定索引或倒数第二个段
const targetPart = pathSegments[2];
// const targetPart = pathSegments.at(-2);

console.log(targetPart);  // 输出: this-is-my-part
方案3:Bash 命令行实现

如果是在终端里处理,用awk或cut就能快速提取:

url="https://example.com/something/this-is-my-part/10448887"

# 方法1:用cut按/分割,取第5个字段
echo $url | cut -d'/' -f5

# 方法2:用awk取倒数第二个字段(更灵活,适配路径段变化)
echo $url | awk -F'/' '{print $(NF-1)}'
方案4:正则表达式通用方案

如果URL结构有规律(比如目标段后面永远跟着数字ID),用正则能精准匹配:

# Python示例
import re

url = "https://example.com/something/this-is-my-part/10448887"
match = re.search(r'/([a-z0-9-]+)/\d+$', url)
if match:
    print(match.group(1))  # 输出: this-is-my-part

这个正则会匹配/后跟着字母、数字、横杠的片段,再后面是/加数字结尾的结构,精准捕获目标部分。

简单总结:如果URL结构固定,路径分割法更简单可靠;如果结构有变化但目标段有规律,正则表达式会更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:25:33