PHP Regex获取url段

时间:2012-11-29 14:55:17

标签: php regex

任何人都可以帮忙吗?

我想获得网址的前两个部分 例如,网址可能如下所示

/catalog/category-1

/catalog/category-1/filter/value

我目前的正则表达式看起来像这样......

/(\/catalog\/.*?)\//

这适用于长网址,但不适用于第一个示例。

4 个答案:

答案 0 :(得分:6)

尝试

$url = explode('/', trim($url, '/'));
$first_segment = $url[0];
$second_segment = $url[1];

编辑: 正如@Crisp在评论中所指出的那样,为了防止在你trim之前将explode空字符串清空{{1}}。

答案 1 :(得分:3)

请勿使用正则表达式来解析您的网址。使用内置的parse_url()功能。

从该函数获取路径组件后,您可以使用explode()函数根据斜杠拆分URL部分。

<?php

$url = "http://example.com/this/that/other?page=1";

$parts = parse_url($url);

print 'Parts = ';
print_r($parts);

print 'Path = ' . $parts['path'] . "\n";

$path_components = explode( '/', $parts['path'] );
print "Path components = ";
print_r( $path_components );

?>

这给你这个:

Parts = Array
(
    [scheme] => http
    [host] => example.com
    [path] => /this/that/other
    [query] => page=1
)
Path = /this/that/other
Path components = Array
(
    [0] => 
    [1] => this
    [2] => that
    [3] => other
)

答案 2 :(得分:1)

Regex在这种情况下不是最好的工具,正如其他人指出的那样,但这里使用的是regex

regex的问题是您要尝试匹配三个/,而是使用否定:

$str1='/catalog/category-1';
$str2='/catalog/category-1/filter/value';

preg_match('#/[^/]*/[^/]*#',$str1,$match);
echo $match[0].;

preg_match('#/[^/]*/[^/]*#',$str2,$match);
echo $match[0];

输出:

/catalog/category-1
/catalog/category-1

说明:

/      # Match first /
[^/]*  # Match anything not a /
/      # Match second /
[^/]*  # Match anything not a /

答案 3 :(得分:0)

首先,使用parse_url将url拆分为主机,端口,路径和查询字符串。

然后,在路径上使用此正则表达式:

<?php
preg_match('#^/([^/]+)/([^/]+)#i', $path, $matches);
?>