Processing URL parameters - pairs of digit values ​​separated by a slash

I want to have URLs like: -

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

I need a PHP code that takes the above URLs as a parameter and returns an array like

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

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

There can be any number of parameters.

I got this idea from the CodeIgniter URL Processing Library. But my project is not on Codeigniter, so I can not use this library. Any separate code for this?

Thanks in advance

+3
4

. , URL-, parse_url . URL-.

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
)

, , . , (, ), .

+5

PHP parse_url http://php.net/manual/en/function.parse-url.php

$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

, path .

, explode, -?

0

php explode. , $result 1 . . Zend_router, -, , // $request.

$result = explode('/', $string);
0
$url    = parse_url('http://www.projectname.com/module/search/param/1');
$params = explode('/', trim($url['path'], '/'));
$params = array_chunk($params, 2); //tricky part here
foreach($params as $param)
{
    $final_params[$param[0]] = $param[1];
}

edit: parse_url URL-

array_chunk - :)

0

Source: https://habr.com/ru/post/1752239/


All Articles