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
https://forums.phpfreaks.com/topic/291031-can-this-be-simplified-with-regex/
Share on other sites

  • 4 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.