在PHP中检查URL的更好方法

时间:2012-10-28 12:38:45

标签: php arrays pattern-matching

这样做有更好的方式或优雅吗?我一直在使用这段代码来检查数据库中基于模式提供的类似URL。

    $menu_selected = '';
$uri_array = explode('/','commodity/statement/flour/factory/');
    $menus = array(
        'commodity/search/flour/factory/index',
        'commodity/statement/sugar/branch/index'
    );

    $pattern_parts = explode('/', '=/*/=/=/*');

foreach ($menus as $menu) {
    $url_parts = explode('/',$menu);

    if( count($pattern_parts) == count($url_parts) ){

        #[i] Trim down for wildcard pattern
        foreach($pattern_parts as $i => $part ){
            if( $part == '*' ) {
                unset($pattern_parts[$i]);
                unset($url_parts[$i]);
                unset($uri_array[$i]);
            }
        }

        #[i] Join array and compare
        if( join('/', $uri_array) == join('/', $url_parts) ) {
            // Found and return the selected
            $menu_selected = $menu; 
            break;
        }
    }
}

0 个答案:

没有答案