find pattern element in array by regular expression and array

时间:2015-12-10 01:14:02

标签: php arrays regex preg-replace

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].

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???
                }
            }
}

2 个答案:

答案 0 :(得分:1)

假设你想要:

// $bestRoute = to the content of $routes[3]
$bestRoute = pathfinderFunc($routes, array ([year] => '2012', [day] => '11', [month] => '01' ));

以下函数采用$routes数组和关联数组(如示例)。它尝试将关联数组的所有键与$routes中的字符串进行匹配。如果找到匹配项,则返回包含匹配路由的数组的内容。如果未找到匹配项,则返回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
}

答案 1 :(得分:0)

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.

Hope this helps