phpapachemod-rewriteurl-rewriting

Is it possible to use RewriteRules to parse these variables from a URL?


I want to make a URL with different categorised variables. The first variable ({variable01}) is vegetables; the second ({variable02}) is fruits; the third ({variable03}) is trees, etc.

The URL thus looks like example.com/{variable01}-{variable02}-{variable03}-{variable04}-......

However, what if a variable has two or three words, and the separator is also a hyphen (e.g., brussels-sprouts)?

This would give example.com/brussels-sprouts-{variable02}-{variable03}-{variable04}-...... Another example might be the fruit green-apple.

How can this be possible?


Solution

  • There is no way to specify the boundaries of your variables anymore, so it's only possible if you know the exact amount of variables and only 1 of your variables may contain hyphens. You can create a regex for that:

    First variable:

    ^([\w-]+)-(\w+)-(\w+)-(\w+)$
    

    Second variable:

    ^(\w+)-([\w-]+)-(\w+)-(\w+)$
    

    But: if you know that each variable can have at most 1 hyphen, you can also do this:

    /var1-foo1-var2-foo2-var3-foo3-var4

    RewriteRule ^(\w+(-\w+)?)-(\w+(-\w+)?)-(\w+(-\w+)?)-(\w+(-\w+)?)$ index.php?var1=$1&var2=$3&var3=$5&var4=$7 [L]
    

    Which results in:

    array (
        'var1' => 'var1-foo1',
        'var2' => 'var2-foo2',
        'var3' => 'var3-foo3',
        'var4' => 'var4',
    )