PHP: Needing regex to camelCase a dashed/underscored string & test result against native PHP functions
I'm trying to streamline this method down. It basically takes in an action (string), makes dashed/underscored strings into camelCase and then tests if the result is equivalent to a native php function, if so it gets an underscore in front. I'm thinking all this could be one regex but I'm not sure how I'd test function_exists. Any help is greatly appreciated!
public function getMethod($action){
if (strpos($action, '-') !== false){
$action = str_replace(' ', '', ucwords(str_replace('-', ' ', $action)));
$action = lcfirst($action);
}
if (strpos($action, '_') !== false){
$action = str_replace(' ', '', ucwords(str_replace('_', ' ', $action)));
开发者_开发知识库 $action = lcfirst($action);
}
// resolves native function names with underscore
if (function_exists($action)) return "_".$action;
else if ($action == 'list') return '_list';
else if ($action == 'new') return '_new';
else if ($action == '') return 'index';
else return $action;
}
After some more research and work I resulted with this:
public function getMethod($action){
$pattern = array('/_(.?)/e', '/-(.?)/e', '/ (.?)/e');
$action = preg_replace($pattern, 'strtoupper("$1")', $action);
if (function_exists($action) || $action == 'list' || $action == 'new' || $action == 'sort')
return '_'.$action;
else if ($action == '')
return 'index';
else
return $action;
}
精彩评论