从完整的URL中提取第一个URL段

7

如何从完整的URL中提取第一个URL段? 第一个URL段应该被清理以将-替换为一个空格

完整的URL

http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020

期望输出

River Island

1
你尝试过什么?(http://whathaveyoutried.com/) - Joseph Silber
我尝试使用str_replace()将“-”替换为空格。不幸的是,我无法弄清楚正则表达式部分以提取第一个URL段。 - Nyxynyx
5个回答

14

你可以使用:

$url = 'http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020';
$parsed = parse_url($url);
$path = $parsed['path'];
$path_parts = explode('/', $path);
$desired_output = $path_parts[1]; // 1, because the string begins with slash (/)

1
+1 用 parse_url,不过我会使用 parse_url($url, PHP_URL_PATH) - Joseph Silber
1
我使用了 $desired_output = $path_parts[1];,它完美地工作了。 - Nyxynyx
你也可以使用 //explode("/",trim($path, "/")); 来去除噪音,并使用 reset 来获取第一个元素 //$output=reset($path_parts); - Goca

2
$page = explode('/', substr($_SERVER['REQUEST_URI'], 1), 2);
echo str_replace("-"," ", $page[0]);

1

稍微修改了一下,将第一个段排除并获取nginx配置中的其他所有内容,像这样 ^\/[^\/]+\/(.*)。这有助于构建带有独立子目录控制器的SEO友好的URL。点赞! - Christos Lytras

0
$path = parse_url($url, PHP_URL_PATH);
$first = substr($path, 0, strpos($path, '/'));

查看这三个函数的文档。也许你需要从路径开头去掉一个斜杠,我不确定。


-2

你有使用过 CodeIgniter 吗?那就可能是这个原因。

$this->uri->segment(segment number of url);

并且在控制器中需要加载uri库


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接