dongyi3616 2010-06-29 09:29
浏览 241
已采纳

处理URL参数 - 由斜杠分隔的名称值对

I want to have URLs like :-

URL 1 -    www.projectname/module/search/param/1
URL 2 -    www.projectname/param/1/module/search

I want a PHP code which takes the above URLs as parameter and returns an array like

Array("module" => "search", "param" => 1) (for URL 1)
Array("param" => 1, "module" => "search") (for URL 2)

So that I can use the result as $_GET in my project. I came to know that it would be better and easier to do this with PHP than with htaccess rewrite rules. If you can help with rewrite rules also please help.

There can be any number of parameters.

I got this idea from CodeIgniter's URL handling library. But my project is not on Codeigniter so I cant use that library. Any standalone code to do that?

Thanks in advance

  • 写回答

4条回答 默认 最新

  • doudandui1592 2010-06-29 10:14
    关注

    Here's a function to do the job. Note that I've filled out the URLs, as parse_url needs the scheme. It will also fail on seriously malformed URLs.

    function get_dispatch($url) {
        // Split the URL into its constituent parts.
        $parse = parse_url($url);
    
        // Remove the leading forward slash, if there is one.
        $path = ltrim($parse['path'], '/');
    
        // Put each element into an array.
        $elements = explode('/', $path);
    
        // Create a new empty array.
        $args = array();
    
        // Loop through each pair of elements.
        for( $i = 0; $i < count($elements); $i = $i + 2) {
            $args[$elements[$i]] = $elements[$i + 1];
        }
    
        return $args;
    }
    
    print_r(get_dispatch('http://www.projectname.com/module/search/param/1'));
    print_r(get_dispatch('http://www.projectname.com/param/1/module/search'));
    

    Here's the result:

    Array
    (
        [module] => search
        [param] => 1
    )
    Array
    (
        [param] => 1
        [module] => search
    )
    

    However, this probably is not very robust. If there is a well written library out there that already does the job (like the one suggested by Itay Moav), then you should definitely look into it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了