I'm struggling to convert .htaccess rule into PHP regex if statement, here's the rule as it is in htaccess
RewriteRule ^user/([a-zA-Z0-9-]+)$ user.php?slug=$1 [L]
Now for PHP I've tried several ways, as i'm not too good with REGEX nothing seems to work.
if(preg_match("#user\/(a-z_\-0-9)\$#",$request)) {
exit("okKKKKKK");
} else {
exit("no");
}
$request is "/user/test-user" anyone could give me a hand?
That is not correct translation. Use this equivalent preg_match
regex:
preg_match("#^/user/([a-zA-Z0-9-]+)$#", $request);
Remember rewrite rules in .htaccess
have missing leading slash as .htaccess
is per directory directive.
You can use the same regular expression you have in your .htaccess
, just place a forward slash before user.
if (preg_match("#^/user/([a-zA-Z0-9-]+)$#", $request)) { ...
It should be probably something like this
if(preg_match("#^\/user\/[a-z_\-0-9]+\$#i",$request)) {
exit("okKKKKKK");
} else {
exit("no");
}
In my opinion you should also track uppercase (i) modifier and make 301 redirects to lowercase url if user exists