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

PHP中如何移除永久链接前缀提取可变页面标题?

嘿,我来帮你搞定这个从永久链接里提取页面标题的问题!

首先得提一下你代码里的小细节——变量定义后面漏了分号,这会直接导致PHP语法报错,先给你修正后的基础版本:

$string = 'http://example.com/blog/PageTitle';
$remove_text = 'http://example.com/blog/'; // 补上分号
$count = strlen($remove_text); // 这里也补上分号
echo substr($string, $count);

不过你说$string和前缀是可变的,比如可能是http://example.com/about/PageTitle或者http://example.com/contact/PageTitle2,那上面这种固定前缀的方法就不够灵活了。给你几个更通用的方案:

方法一:找最后一个斜杠的位置提取标题

不管前缀是什么结构,只要页面标题在URL的最后一个斜杠后面,就可以用strrpos定位最后一个斜杠的位置,再截取后面的内容:

$string = 'http://example.com/about/PageTitle';
// 找到最后一个/的位置
$lastSlashPos = strrpos($string, '/');
// 从最后一个/的下一位开始截取
$pageTitle = substr($string, $lastSlashPos + 1);
echo $pageTitle; // 输出 PageTitle

这个方法最通用,不管你的前缀是/blog/、/about/还是其他任意结构,都能准确提取到最后面的标题部分。

方法二:用parse_url和basename组合提取

先解析URL拿到路径部分,再用basename获取路径的最后一段:

$string = 'http://example.com/contact/PageTitle2';
// 解析URL,分离出各个部分
$urlParts = parse_url($string);
// 获取路径的最后一段
$pageTitle = basename($urlParts['path']);
echo $pageTitle; // 输出 PageTitle2

如果你的标题后面带了后缀(比如.html),还可以搭配pathinfo去掉后缀:

$string = 'http://example.com/blog/PageTitle.html';
$urlParts = parse_url($string);
$path = $urlParts['path'];
// 获取不带后缀的文件名
$pageTitle = pathinfo($path, PATHINFO_FILENAME);
echo $pageTitle; // 输出 PageTitle

方法三:动态匹配前缀(适合明确前缀规律的场景)

如果你的前缀都是「域名+一级目录」的结构,比如http://example.com/xxx/,可以先动态提取前缀再替换:

$string = 'http://example.com/services/ServiceTitle';
$domain = 'http://example.com/';
// 找到域名后第一个斜杠的位置
$dirEndPos = strpos($string, '/', strlen($domain));
// 提取完整前缀
$removeText = substr($string, 0, $dirEndPos + 1);
// 替换前缀得到标题
$pageTitle = str_replace($removeText, '', $string);
echo $pageTitle; // 输出 ServiceTitle

不过这个方法不如前两种通用,更适合你明确知道前缀结构的场景。

总结一下,最推荐用方法一或者方法二,适配各种可变前缀的情况,代码简洁还可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:07:39