处理URL参数-名称值对用斜杠分隔 [英] Processing URL parameters - name value pairs separated by slashes

查看:208
本文介绍了处理URL参数-名称值对用斜杠分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要类似:-

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

我想要一个将上述URL作为参数并返回一个像这样的数组的PHP代码

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)

这样我就可以在项目中将结果用作$ _GET了.我知道,用PHP进行此操作比使用htaccess重写规则会更好,更容易.如果您还可以提供重写规则方面的帮助,请提供帮助.

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.

我从CodeIgniter的URL处理库中得到了这个想法.但是我的项目不在Codeigniter上,所以我不能使用该库.有任何独立的代码可以做到这一点吗?

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?

预先感谢

推荐答案

这是完成这项工作的功能.请注意,我已经填写了URL,因为parse_url需要该方案.如果网址格式严重错误,也会失败.

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'));

结果如下:

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

但是,这可能不是很可靠.如果那里有一个写得很好的库已经可以完成这项工作(例如Itay Moav建议的库),那么您绝对应该研究一下.

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.

这篇关于处理URL参数-名称值对用斜杠分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆