我正在尝试编写一个regualr表达式来匹配无效的url模式
我想匹配以下模式:
/article/test-string/
以上是无效的网址,但以下是有效的
/article/abc/test-string/ and /article/xyz/abc/test-string/
我希望匹配文章斜杠后只有一个值的那些。 请帮助,我正在尝试使用以下,但它匹配所有:
/article/(.*)/$
答案 0 :(得分:2)
.*
匹配任何字符的0个或更多,因此/article/(.*)/$
将匹配其中包含/article/
的所有URI。
您可以使用此正则表达式仅在/article/
之后验证一个非斜杠组件:
$re = '~^/article/[^/]*/$~';
[^/]*
#匹配任何不是/
/$
#匹配最后的/
~
用作正则表达式分隔符,以避免转义/
答案 1 :(得分:1)
~^/article/(.*)+/(.*)/$~gm ^ assert position at start of a line /article/ matches the characters /article/ literally (case sensitive) 1st Capturing group (.*)+ Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data .* matches any character (except newline) Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] / matches the character / literally 2nd Capturing group (.*) Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data .* matches any character (except newline) Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] / matches the character / literally $ assert position at end of a line g modifier: global. All matches (don't return on first match) m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
$re = "~^/article/(.*)+/(.*)/$~m";
$str = "/article/xyz/abc/test-string/\n/article/test-string/";
preg_match_all($re, $str, $matches);