带有“:”的友好网址

时间:2012-05-30 23:08:47

标签: php regex friendly-url

我有以下代码,获取$_GET并通过控制器,操作和参数进行划分

http://localhost/controller/action/param1/param2

$url = explode('/', $_GET['url']);
$urlSize = count($url);
$filter = $this->factory('Core\Security\Filter');

if($urlSize >= 1) {
    $controller = $filter->replace($url[0], 'friendly-url');

    if($urlSize >= 2) {
        $action = $filter->replace($url[1], 'friendly-url');

        if($urlSize >= 3) {
            unset($url[0], $url[1]);

            foreach($url as $index => $param) {
                $params[] = $filter->replace($param, 'friendly-url');
            }
        }
    }
}
我正在开发的

Core\Security\Filter->replace()

public function replace($data = null, $type = 'alphanumeric') {
    /*
        @TODO, implement regex by type

        numeric
                $regex = '/^[[:digit:]]$/';
        alphanumeric
                $regex = '/^[[:alnum:]]$/';
        friendly-url
                $regex = '/[^a-zA-Z0-9_-]+/';
                $replace = '-'
        username
                $regex = '/^[^a-zA-Z0-9_-.]{3,32}+';
        email
                $regex = '/^[[a-zA-Z0-9_-.]{1,96}]+@[a-zA-Z0-9-]{2,64}+(?:\.[a-zA-Z0-9-]+)*$/';
    */
}

好的,我遇到的问题是:如何获取这种格式的网址:

http://localhost/controller/action/param1/param2:value2

$ param array:

Array(
    [0] => param1
    [1] => Array(
       [param2] => value2
    )
)

解决了这个问题:

foreach($url as $index => $param) {
    if(strstr($param, ':')) {
        $subParam = explode(':', $param, 2);
        $this->_request['params'][][$subParam[0]] = $filter->replace($subParam[1], 'friendly-url-param');
    } else {
        $this->_request['params'][] = $filter->replace($param, 'friendly-url-param');
    }
}

1 个答案:

答案 0 :(得分:2)

<?php

$url = 'http://localhost/controller/action/param1/param2:value2';

$parts = parse_url($url);
$path = $parts['path'];

list($controller, $action, $params) = explode('/', ltrim($path, '/'), 3);

function parse_params($params) {
    $parsed_params = array();
    $path_segments = explode('/', $params);
    foreach ($path_segments as $path_segment) {
        if (strstr($path_segment, ':')) {
            list($k, $v) = explode(':', $path_segment, 2);
            $parsed_params[] = array($k => $v);
        } else {
            $parsed_params[] = $path_segment;
        }
    }
    return $parsed_params;
}



$params = parse_params($params);

print_r($params);

<强>输出

Array
(
    [0] => param1
    [1] => Array
        (
            [param2] => value2
        )

)