URI解析的正则表达式

时间:2017-05-02 16:58:10

标签: php regex preg-match

我写的小框架。无法转到网址/page/test。说page not found。也许urls.php中的正则表达式有问题?看起来浏览器会处理URL本身,但脚本应该如此。

<?php

class griEngine {

public
    $settings, //settings
    $uri,  //current URI
    $app;  //curent app

public function __construct($settings) {

    $this->settings= $settings;
    $this->uri = urldecode(preg_replace('/\?.*/iu','',$_SERVER['REQUEST_URI']));
    $this->app = false;
    $this->process_path();
    $this->process_controllers();

}

public function process_path() {

    foreach( $this->settings['apps'] as $iterable_app )
    {
        $iterable_urls = require(BASE_DIR. '/apps/'. $iterable_app. '/urls.php');
        foreach( $iterable_urls as $pattern => $method)
        {
            $matches = array();
            if (preg_match($pattern, $this->uri, $matches))
            {

                $this->app = array($iterable_app, array('pattern' => $pattern, 'method' => $method, 'args' => $matches));
                break(2);


    }

    if( $this->app ==='false')
    {
        exit('App not found.');
    }
}

public function process_controllers() {

    if ($this->app || is_array($this->app))
    {
        require(BASE_DIR.'/apps/'.$this->app['0'].'/controller.php');
        $controller_name = $this->app['0'].'_Controller';
        $this->app_controller = new $controller_name();
        $this->app_controller->{$this->app['1']['method']}($this->app['1']['args']);
    } 
}


}

文件urls.php

<?php

return array(

'#^/*$#i' => 'MainPage',
'#^/Page/([A-z0-9_-])/*#i' => 'ViewPage'

);

file controller.php

<?php


class Simple_Pages_Controller extends gri_Controller {

public function MainPage($args){
    echo 'Hello world';
}


public function ViewPage(){
    echo 'test';
}
}
?>

1 个答案:

答案 0 :(得分:0)

您在+ ^/Page/([A-z0-9_-])/*#i遗失了test。由于/page/test中的1包含的字符数超过+,因此您应该使用return array( '#^/*$#i' => 'MainPage', '#^/Page/([A-z0-9_-])/*#i' => 'ViewPage' );

将其更改为:

<?php
return array(

'#^/*$#i' => 'MainPage',
'#^/Page/([A-z0-9_-]+)/*#i' => 'ViewPage'

);

:此:

{{1}}