简体   繁体   English

具有至少一个连字符的add_rewrite_rules的正则表达式

[英]Regular expression for add_rewrite_rules with at least one hyphen

I'm working with a regular expression for Wordpress' add_rewrite_rules. 我正在使用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. 我的目标是将具有单个目录的URL与至少一个破折号匹配并返回该目录。

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) test/失败(应该是,因为没有连字符)

te-st/ passes, but only returns "st" for the variable. te-st/ pass,但只返回变量的“st”。

te-st-ing/ passes, but only returns "ing" for the variable. te-st-ing/ pass,但只返回变量的“ing”。

te-st-ing/a/ fails (as there's another directory) te-st-ing/a/ failed(因为还有另一个目录)

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. 我对表达式有点失落,但目标是“te-st”会通过,但会返回整个“te-st”字符串。 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. REGEX 101演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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