处理 URL 参数 - 以斜杠分隔的名称值对
我想要这样的 URL:-
URL 1 - www.projectname/module/search/param/1
URL 2 - www.projectname/param/1/module/search
我想要一个 PHP 代码,它将上述 URL 作为参数并返回一个像这样的数组,
Array("module" => "search", "param" => 1) (for URL 1)
Array("param" => 1, "module" => "search") (for URL 2)
这样我就可以在我的项目中使用结果作为 $_GET 。我发现使用 PHP 比使用 htaccess 重写规则更好、更容易。如果您可以帮助重写规则,也请帮忙。
可以有任意数量的参数。
我从 CodeIgniter 的 URL 处理库中得到了这个想法。但我的项目不在 Codeigniter 上,所以我无法使用该库。有独立的代码可以做到这一点吗?
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是完成这项工作的函数。请注意,我已经填写了 URL,因为
parse_url
需要该方案。对于严重格式错误的 URL,它也会失败。结果如下:
但是,这可能不是很稳健。如果有一个编写良好的库已经可以完成这项工作(如 Itay Moav 建议的库),那么您绝对应该研究一下它。
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.Here's the result:
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.
使用 php explode 函数。您必须解析结果并查看 $result1是您的应用程序中的有效模块等等。解析器的逻辑应该属于您的应用程序。有人提到的 Zend_router 通过尝试将其具有的任何 $request 对象映射到现有模块/控制器/操作来执行相同的操作。
Use php explode function. You will have to parse the result and see if the $result1 is a valid module in your application an so on. The logic of the parser should belong to your application. Zend_router that somebody mentioned does the same thing by trying to map to an existing module/controller/action whatever $request object it has.
使用 PHP 函数
parse_url
http://php. net/manual/en/function.parse-url.php因此,您可以分析数组的
path
部分。您冷了然后使用
explode
将项目放入 assoc 数组中吗?Use the PHP function
parse_url
http://php.net/manual/en/function.parse-url.phpSo you can then analyse the
path
section of the array.You cold then use
explode
to put items into an assoc array?编辑: parse_url 仅适用于正确的 URL
array_chunk 是一个很好的函数这个任务:)
edit: parse_url works with correct URLs only
array_chunk is a nice function for this task :)