无法正确匹配和提取字符串中的参数

时间:2013-10-25 06:59:06

标签: php regex

我正在尝试从字符串中提取参数大约2个小时。无论它有多少参数。

考虑这个(例子),

$template = "/category/(:any)/(:any)/(:any)/";
$input    = "/category/username/category-id/2";

And I would like an array of parameters to be like this,

Array (
    [0] => username
    [1] => category-id
    [2] => 2
)

所以,我已经开始了,

$replacements = array(
    '(:any)'        =>  '.+(?=/|$)',
);

$str = '/category/(:any)/(:any)/(:any)';
$str = str_replace(array_keys($replacements), array_values($replacements), $str);

$input = '/category/username/category-id/2';

$pattern = '~^' . $str . '$~';

preg_match($pattern, $input, $matches);

print_r($matches);

// That prints Array ( [0] => /category/username/category-id/2 ) 

但现在我坚持使用适当的参数提取。首先想到的是在两个字符串之间找到相似的值并将其删除。然后移除(:any)/

$template = "/category/(:any)/(:any)/(:any)/";
$input    = "/category/username/category-id/2";

问题在于,需要依赖explode()的大量额外工作。

所以问题是 :(看看第一个代码示例): 如何使用正则表达式正确实现这一点,以便在$matches中匹配并正确放置参数?

3 个答案:

答案 0 :(得分:1)

我相信这个正则表达式应该有效:

$replacements = array(
    '(:any)'        =>  '([^/]*)',
);

$template = "/category/(:any)/(:any)/(:any)/";
$input    = "/category/username/category-id/2";

$str = '/category/(:any)/(:any)/(:any)';
$str = str_replace(array_keys($replacements), array_values($replacements), $str);

$input = '/category/username/category-id/2';

$pattern = '~^' . $str . '$~';

preg_match($pattern, $input, $matches);

print_r($matches);

<强>输出:

Array
(
    [0] => /category/username/category-id/2
    [1] => username
    [2] => category-id
    [3] => 2
)

答案 1 :(得分:1)

您可以使用preg_split()这样的功能:

$pattern = "/[\/]/";
$parameters = preg_split($pattern, "/category/username/category-id/2");
array_shift($parameters);
array_shift($parameters);
var_dump($parameters);

此代码通过分隔符/将字符串拆分为数组。结构是这样的:

array(5) { 
    [0]=> string(0) "" 
    [1]=> string(8) "category" 
    [2]=> string(8) "username" 
    [3]=> string(11) "category-id" 
    [4]=> string(1) "2" 
}

然后使用array_shift() 2次,结果将是:

array(3) { 
    [0]=> string(8) "username" 
    [1]=> string(11) "category-id" 
    [2]=> string(1) "2" 
}

我正在使用 username,category_id,... 这些词语,它们也可能是变量。

答案 2 :(得分:0)

与@ 1linecode相同但不使用正则表达式。

$url = "http://somedomain.com/category/username/category-id/2";
$path = parse_url($url, PHP_URL_PATH);
$params = explode('/', $path);
array_shift($params);
array_shift($params);

输出:

array(3) { [0]=> string(8) "username" [1]=> string(11) "category-id" [2]=> string(1) "2" }