如何使用Regex将URL字符串分成多个部分

时间:2011-05-14 16:16:02

标签: php regex url

我有以下网址字符串

/category/category1/2010/12/10/id

我需要将字符串分成几部分。我正在尝试这种模式

(?:(.*))?(?:(?:\/)?([0-9]{4}))?(?:(?:\/)?([0-9]{1,2}))?(?:(?:\/)?([0-9]{1,2}))?(?:(.*))?

但它无法正常工作

如果网址与此/category/category1/类似,我需要以下代码

path = '/category/category1/';
year = '';
month = '';
day = '';
id ='';

如果网址与此/category/category1/2010类似,我需要以下代码

path = '/category/category1/2010';
year = '2010';
month = '';
day = '';
id ='';

如果网址与此/category/category1/2010/12/类似,我需要以下代码

path = '/category/category1/2010/12';
year = '2010';
month = '12';
day = '';
id ='';

如果网址与此/category/category1/2010/12/10类似,我需要以下代码

path = '/category/category1/2010/12/10';
year = '2010';
month = '12';
day = '10';
id ='';

如果网址与此/category/category1/2010/12/10/id类似,我需要以下代码

path = '/category/category1/2010/12/10/id';
year = '2010';
month = '12';
day = '10';
id ='id';

是否可以使用preg_match和正则表达式进行此操作?

4 个答案:

答案 0 :(得分:6)

为什么不简单地explode('/', $url);

现在你已经有了一些URL片段。如果您还在验证后,您现在可以单独验证每个部分(存在),整个事情将更加清晰。

答案 1 :(得分:1)

PHP:

function findInfo ($path) {
    return array_slice(explode('/', trim($path, '/')), 2);
}

$path = "/category/category1/2010/12/10/id";
list($year, $month, $day, $id) = findInfo($path);

var_dump($path, $year, $month, $day, $id);

$path = "/category/category1/";
list($year, $month, $day, $id) = findInfo($path);

var_dump($path, $year, $month, $day, $id);

$path = "/category/category1/2010/";
list($year, $month, $day, $id) = findInfo($path);

var_dump($path, $year, $month, $day, $id);

$path = "/category/category1/2010/12";
list($year, $month, $day, $id) = findInfo($path);

var_dump($path, $year, $month, $day, $id);

$path = "/category/category1/2010/12/10";
list($year, $month, $day, $id) = findInfo($path);

var_dump($path, $year, $month, $day, $id);

输出:

string(33) "/category/category1/2010/12/10/id"
string(4) "2010"
string(2) "12"
string(2) "10"
string(2) "id"
string(20) "/category/category1/"
NULL
NULL
NULL
NULL
string(25) "/category/category1/2010/"
string(4) "2010"
NULL
NULL
NULL
string(27) "/category/category1/2010/12"
string(4) "2010"
string(2) "12"
NULL
NULL
string(30) "/category/category1/2010/12/10"
string(4) "2010"
string(2) "12"
string(2) "10"
NULL

答案 2 :(得分:1)

你可以使用preg_match。以下正则表达式使用问题中的所有示例进行测试:

$regex = '/^(\\/[^\\/]+\\/[^\\/]+\\/)\\/?([0-9]{4})?\\/?([0-9]{2})?\\/?([0-9]{2})?\\/?(.*)$/';
if (preg_match($regex, $url, $match))
    print_r($match);
else
    die('No match.');

答案 3 :(得分:1)

简单列表()函数

<?php 
$url = 'http://example.com/category/category1/2010/12/10/id';
$url = str_ireplace('http://example.com/','',$url);
/*
category/category1/2010/12/10/id
=
//type/cat/year/month/day/id
using list()
*/
list($type,$cat,$year, $month, $day,$id) = explode('/',$url); 

echo $id.':'.$day.'-'.$month.'-'.$year;

?>