【问题标题】:find pattern element in array by regular expression and array通过正则表达式和数组在数组中查找模式元素
【发布时间】:2015-12-10 01:14:02
【问题描述】:

我有一个字符串数组:

$routes = Array
(
    [0] => Array
        (
            [0] => /
        )

    [1] => Array
        (
            [0] => /articles/[:slug]?
        )

    [2] => Array
        (
            [0] => /articles/[:cid]/[:slug]?
        )

    [3] => Array
        (
            [0] => /articles/[a:year]/?[*:month]?/?[*:day]?
        )
)

还有一个带有下面参数的数据数组。根据这些数据,我想从路线中找到最佳匹配。

Array
(
    [year] => 2012
    [day] => 11
    [month] => 01
)

在上面的例子中:我想获得 $routes[3]

我尝试过这样的事情:

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

【问题讨论】:

  • 1) 你有没有尝试过一些事情来达到你的目标? 2) 为什么元素 3 是“最佳匹配”?
  • 我尝试了一些方法但没有成功。
  • 你应该把它包括在内以帮助潜在的答案。
  • 请用我试过的代码检查我更新的问题

标签: php arrays regex preg-replace


【解决方案1】:

假设你想要:

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

以下函数采用$routes 数组和一个关联数组,如您的示例。它尝试将关联数组的所有键与$routes 中的字符串匹配。如果找到匹配项,则返回包含匹配路由的数组的内容。如果未找到匹配项,则返回 false。

函数 pathfinderFunc($routes, $match) { $keys = array_keys($match); $isMatch = 假; foreach($routes 作为 $route) { foreach($keys 作为 $key) { if(strpos($route[0], $key) === false) 继续2; } 返回$路线; } 返回假; // 没有找到好的匹配 }

【讨论】:

    【解决方案2】:

    我相信他想从路由参数中获取哪个路由号。

    这只是一个想法,取决于你会怎么走。

    我将在下面定义我的路由数组的更多细节以使事情更精确,您可以从参数数量或其他方面进行检查。

    $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;
      }
    
    }
    

    这只是示例,您可能有一些方法可以使用每个路线详细信息的参数详细信息来检查某些内容。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2017-10-16
      相关资源
      最近更新 更多