[英]find pattern element in array by regular expression and array
I have an array of strings: 我有一个字符串数组:
$routes = Array
(
[0] => Array
(
[0] => /
)
[1] => Array
(
[0] => /articles/[:slug]?
)
[2] => Array
(
[0] => /articles/[:cid]/[:slug]?
)
[3] => Array
(
[0] => /articles/[a:year]/?[*:month]?/?[*:day]?
)
)
And a data array with params below. 以及下面带有参数的数据数组。 Based on this data I want to find best match from routes. 基于此数据,我想从路线中找到最佳匹配。
Array
(
[year] => 2012
[day] => 11
[month] => 01
)
In the example above: I want to get $routes[3] . 在上面的示例中:我想获取$ routes [3] 。
I have tried something like this: 我已经尝试过这样的事情:
foreach($routes as $route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route[0], $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
// How to check???
}
}
}
Assuming you want: 假设您要:
// $bestRoute = to the content of $routes[3]
$bestRoute = pathfinderFunc($routes, array ([year] => '2012', [day] => '11', [month] => '01' ));
The following function takes the $routes
array and an associative array like your example. 下面的函数采用$routes
数组和一个与您的示例类似的关联数组。 It tries to match all of the keys of the associative array to the strings in $routes
. 它尝试将关联数组的所有键与$routes
的字符串匹配。 If a match is found, it returns the contents of the array that contains the matched route. 如果找到匹配项,它将返回包含匹配路由的数组的内容。 If no match is found, it returns false. 如果找不到匹配项,则返回false。
function pathfinderFunc($routes, $match) { $keys = array_keys($match); $isMatch = false; foreach($routes as $route) { foreach($keys as $key) { if(strpos($route[0], $key) === false) continue 2; } return $route; } return false; // no good match found }
I believe he wants to get which route number from route params. 我相信他想从路线参数中获取哪个路线号。
And this is just an idea depend on how will you go. 这只是一个想法,取决于您的工作方式。
I will define more details on my route array as below to make things more precise, you can check from number of parameter or whatever. 我将在下面的路由数组中定义更多详细信息,以使事情更加精确,您可以从参数数量或其他任何内容中进行检查。
$routes = array(
[0] => Array
(
[pattern] => /
[param_num] =>0
[params] =>array()
)
[1] => Array
(
[pattern] => /articles/[:slug]?
[param_num] =>1
[params] => array()
)
[2] => Array
(
[pattern] => /articles/[:cid]/[:slug]?
[param_num] =>2
[params] => array()
)
[3] => Array
(
[0] => /articles/[a:year]/?[*:month]?/?[*:day]?
[param_num] =>3
[params] => array('year', 'month', 'day')
));
/*
Array
(
[year] => 2012
[day] => 11
[month] => 01
)
*/
$param_count = count($params);
$select_route = null;
foreach( $routes as $route){
if( $route['param_num'] == $param_count){
$select_route = $route;
break;
}
}
This is just example , you may have some way to use params details of each route detail to check something. 这只是示例,您可能有某种方法可以使用每个路由详细信息的params细节来检查某些内容。
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.