Regular expression for add_rewrite_rules with at least one hyphen

I’m working with a regular expression for WordPress’ add_rewrite_rules.

My goal is to match URLs that have a single directory with at least one dash in there and return that directory.

Read More

I was able to find this:

'^([a-zA-Z0-9]*-[a-zA-Z0-9]*){1,20}/?$' => 'index.php?pagename=location&location=$matches[1]'

This matches if there is a hyphen, but returns only the end of the string (the part after the last hyphen).

So:

test/ fails (as it should, since there’s no hyphen)

te-st/ passes, but only returns “st” for the variable.

te-st-ing/ passes, but only returns “ing” for the variable.

te-st-ing/a/ fails (as there’s another directory)

I’m a bit lost with expressions, but the goal is that “te-st” would pass but would return with the whole “te-st” string. I think that should be an easy fix for someone who knows how to deal with expressions?

Thanks!

Related posts

2 comments

  1. Just to ensure at least one hyphen is there you can use:

    '^([^-/]*-[^/]*)/?$' => 'index.php?pagename=location&location=$matches[1]'
    

Comments are closed.