1

我坐了大约 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

4

3 回答 3

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
)
于 2013-10-25T07:04:33.297 回答
1

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

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

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

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、...这些词,它们也可能是变量。

于 2013-10-25T07:18:57.440 回答
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" }
于 2013-10-25T07:27:38.490 回答