簡體   English   中英

通過正則表達式和數組在數組中查找模式元素

[英]find pattern element in array by regular expression and array

我有一個字符串數組:

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

假設您要:

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

我相信他想從路線參數中獲取哪個路線號。

這只是一個想法,取決於您的工作方式。

我將在下面的路由數組中定義更多詳細信息,以使事情更加精確,您可以從參數數量或其他任何內容中進行檢查。

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

}

這只是示例,您可能有某種方法可以使用每個路由詳細信息的params細節來檢查某些內容。

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM