Solution:
public function getMethod($action) {
// Patterns to match underscores, dashes, or spaces followed by a character
$pattern = array('/_(.?)/e', '/-(.?)/e', '/ (.?)/e');
// Replace matched character with its uppercase version to convert to camelCase
$action = preg_replace($pattern, 'strtoupper("$1")', $action);
// Check if function exists or is a reserved method name
if (function_exists($action) || in_array($action, ['list', 'new', 'sort'])) {
return '_'.$action; // Prefix with underscore if it’s a reserved name
} elseif ($action == '') {
return 'index'; // Default method if empty
} else {
return $action;
}
}
Notes & Modern PHP Update
Deprecated /e modifier:
The /e modifier in preg_replace is deprecated in PHP 5.5+ and removed in PHP 7.
Use preg_replace_callback instead for safer modern code.
Modern version using preg_replace_callback:
public function getMethod($action) {
$action = preg_replace_callback('/[_\-\s](.?)/', function($matches) {
return strtoupper($matches[1]);
}, $action);
if (function_exists($action) || in_array($action, ['list', 'new', 'sort'])) {
return '_'.$action;
} elseif ($action == '') {
return 'index';
} else {
return $action;
}
}
This approach safely converts my_function-name or my function name → myFunctionName.
Works in PHP 7+ without deprecated warnings.