Pretty URL change variable seporator

51 views Asked by At

I am trying to pass variables by a pretty url which I can achive using the following:

domain.com/exercises/lunge+with+dumbells

And this in my .htaccess file:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9+]+)$ index.php?exercise=$1
RewriteRule ^([a-zA-Z0-9+]+)/$ index.php?exercise=$1

Which is accessed in php using:

$urlVars = $_GET["exercise"];

However, I need my URLs to read like this:

domain.com/exercises/lunge-with-dumbells

I can get this to work using

exercises/?exercise=lunge-with-dumbells and this PHP function:

$urlVars = $_GET["exercise"];
$newString = str_replace("-", " ", $urlVars);

however, I would like a pretty URL with the variable string separated by - rather than +

Many thanks.

1

There are 1 answers

0
kawashita86 On BEST ANSWER

To let your .htaccess match an url prettified with a "-" separator rather than a "+" separator you just need to change the regular expression that manages the rewrite rule to your php file:

Change the rules from:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9+]+)$ index.php?exercise=$1
RewriteRule ^([a-zA-Z0-9+]+)/$ index.php?exercise=$1

to:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9-]+)$ index.php?exercise=$1
RewriteRule ^([a-zA-Z0-9-]+)/$ index.php?exercise=$1

to split the regular expression in it's simplest components, we are going to create one that says

   ^ // match the beginning of a strings that start with
   ( 
   [ // a pattern consisting of
    a-z //a lowercase alphabet letter
    A-Z //a uppercase alphabet letter
    0-9 //a digit
    - //and the minus sign (here we changed from the + sign to the new value)
    ]
    + //one or more occurence of the combination described above
    )

for more details about regular expression and .htaccess please refer to : https://httpd.apache.org/docs/current/rewrite/intro.html