简体   繁体   中英

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.

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!

只是为了确保至少有一个连字符,你可以使用:

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

Please try this pattern:

^((?:\w+-){1,20}\w*)/?$

REGEX 101 DEMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM