Jump to content

Can this be simplified with regex?


deathbeam

Recommended Posts

So, I am not very experienced with regexes, so I wanna ask if this code can be simplified with preg_match? It is code from my framework on what I am working for adding routes. To explain what is "default" and "MAP", here is example usage. And, callable is called via call_user_func_array if that helps.

// mapping routes
$fw->route('home: GET|POST /', 'home');

// provide ReST interface by mapping HTTP requests to class method
$fw->route('MAP /rest', 'some_class');

// default route (404 page)
$fw->route('default', 'error');

And this is route method.

public function route($pattern, $callable) {
		$pattern = strtr($pattern,array(' '=>''));
		
		if ($pattern == 'default') {
			$this->default_route = $callable;
			return $this;
		}

		$arr = explode('/', $pattern, 2);
		$method = $arr[0];
		$route = '/'.$arr[1];
		
		if (strpos($arr[0], ':') !== false) {
			$arr = explode(':', $arr[0], 2);
			$name = $arr[0];
			$method = $arr[1];
		}
		
		if ($method == 'MAP') {
			foreach ((explode('|', self::Methods)) as $method) {
				$this->route((isset($name)?$name.':':null).$method.$route, $callable.'->'.strtolower($method));
			}
			return $this;
		}
		
		$this->routes[] = array($method, $route, $callable, isset($name)?$name:null);
		return $this;
	}
Link to comment
Share on other sites

  • 4 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.