regex for MVC router
<?php
$regexarray = [
"@^$@i", // for homepage
"@^(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)$@i", // controller/action
"@^(?P<controller>[a-z-]+)/(?P<id>\d+)/(?P<action>[a-z-]+)$@i", // users/4/delete
"@^admin/(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)$@i", // admin/users/index
"@^admin/(?P<controller>[a-z-]+)/(?P<id>\d+)/(?P<action>[a-z-]+)$@i" // admin/users/4/edit
] ;
foreach( $regexarray as $route ) {
if( preg_match($route, "admin/users/78/delete", $matches) ) {
echo "FOUND MATCH " . PHP_EOL;
}
}
// #####################################################
$admin = "@^$@i";
/* will match:
empty url, this is the homepage
*/
$admin = '@^admin/(?P<controller>[a-z-]+)/(?P<id>\d+)/(?P<action>[a-z-]+)$@i';
/* will match:
admin/users/78/delete
*/
$admin = "@^(?P<controller>[a-z-]+)\/(?P<id>\d+)\/(?P<action>[a-z-]+)$@i" ;
/* will match:
user/4/edit
*/
$admin = "@^(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)$@i";
/* will match:
user/login
user/registration
*/
if( preg_match($admin, "", $matches) ) {
echo "FOUND MATCH" . PHP_EOL;
}
else {
echo "NOT FOUND" ;
}