Preg_match_all,但如果通配符包含斜杠则停止


preg_match_all but stop if wildcard contains a slash

假设我有这个正则表达式:'#artists/(.*)/#',我想匹配这个字符串:'/artists/alesana/wires-and-the-concept-of-breathing/',我怎么能确保它只匹配'alesana'而不是'alesana/wires-and-the-concept-of-breathing'

换句话说,我怎样才能让我的regexp与斜杠相连。严格来说,我将为artists/(.*)/(.*)创建另一个路由规则但我知道我迟早会在其他地方遇到这个问题

使用?字符使正则表达式不贪婪。这基本上会找到最短的匹配:

/artists/(.*?)/

阅读更多:正则表达式中的惰性量化

你试过吗?artists/[^/].+?/

Hans Engel提到的非贪婪搜索的另一个解决方案是:

/artists/([^/]*)/

在字符类[]中使用^将否定内容。因此,[^/]将匹配除斜杠以外的所有字符。

您可以在http://www.regular-expressions.info/reference.html上阅读更多关于正则表达式和元字符的信息