Ignore the second "-" in a modrewrite rule

Here is my rewrite rule:

Options -MultiViews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([^-])-([^-])\.php$ /view.php?m=$1&c=$2 [L]

Here is my link structure:


Here is the url I want to work, but it doesn’t:


This url looks great but the url doesn’t work because the “black-ford” has a “-”

Is there anyway to rewrite my rewrite rule to ignore any "-"s after
the first one?

$1 and $2 are only alpha characters? If so, I’d go for

Options -MultiViews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([a-zA-Z]+)-([a-zA-Z-]+)\\.php$ /view.php?m=$1&c=$2 [L]

The first atom can only match a-z and A-Z (small chars and caps), followed by a hyphen, and then an atom that can match a-z, A-Z and hyphens, so all extra hyphens will be matched by the second atom.

PS. If the first part can also contain hyphens it can’t be done anymore.

I’m close to having it, but I need to allow numbers in the first expression.

Options -MultiViews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)-([a-zA-Z-]+)\.php$ /alpha/view.php?m=$1&c=$2 [L]

Does this look good to you?

Apart from the fact that you could (but don’t have to) write

Options -MultiViews
Options +FollowSymLinks


Options -MultiViews +FollowSymLinks

yes, looks fine :tup:


It’s best to escape hyphens:


That’s debatable :slight_smile:

I always opt to type as little as possible when coding while still maintaining readability, which is why I adopted the method to always put the - at the end of a character class and forget about escaping.

But indeed, if the hyphen is either at the start or the end of the character class you don’t have to escape it, if it’s anywhere else you must. I suppose that as a rule of thumb it might be good to do it.

Good point! :slight_smile:

Also, not all regex engines will necessarily recognize unescaped hyphens, so best to get in the habit of escaping them, just so you don’t go bonkers if you encounter an engine that doesn’t handle less explicit formatting.

I’m all for simplicity in proprietary systems, but when using open standards like regex, SQL, etc., I try to use what’s most cross-system compatible.