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

如何在PHP中移除Google Sheet URL字符串的末尾部分?

PHP解析Google Sheet URL并移除末尾多余部分

针对Google Sheet URL中/edit#gid=xxxxxxx这类末尾部分的移除需求,提供三种实用实现方式:

方法一:字符串定位截取

通过查找/edit的位置直接截取目标部分,逻辑简单直观:

$string = 'https://docs.google.com/spreadsheets/d/xxxx/edit#gid=xxxxxxx';
$editPos = strpos($string, '/edit');
$string_parsed = $editPos !== false ? substr($string, 0, $editPos + 1) : $string;
// 输出结果:https://docs.google.com/spreadsheets/d/xxxx/

方法二:正则表达式替换

用正则匹配/edit及后续所有内容,替换为结尾斜杠,适配更多参数变体:

$string = 'https://docs.google.com/spreadsheets/d/xxxx/edit#gid=xxxxxxx';
$string_parsed = preg_replace('/\/edit.*/', '/', $string);
// 输出结果:https://docs.google.com/spreadsheets/d/xxxx/

方法三:标准URL解析拼接

借助PHP内置URL解析函数拆分重组,处理逻辑更规范,兼容复杂URL场景:

$string = 'https://docs.google.com/spreadsheets/d/xxxx/edit#gid=xxxxxxx';
$urlParts = parse_url($string);
$pathParts = explode('/edit', $urlParts['path'], 2);
$newPath = $pathParts[0] . '/';
$string_parsed = $urlParts['scheme'] . '://' . $urlParts['host'] . $newPath;
// 输出结果:https://docs.google.com/spreadsheets/d/xxxx/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:25:25