本文介绍了Laravel-正则表达式路由匹配所有内容,但不完全匹配一个或多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我沿着这样的路线

Route::get('/{url1}', function ($url1) {
    return ' url1: '.$url1;
})
->where('url1', '^(?!(string1|string2)$)');

并访问如下网址:
-domain/abc 未找到=>不正确 ??
-找不到domain/string1 =>正确

and access url like:
- domain/abc not found => incorrect ??
- domain/string1 not found => correct

还有更多,当我这样做时

and more, when i do with

Route::get('/{url1}/{url2}', function ($url1) {
    return ' url1: '.$url1;
})
->where('url1', '^(?!(string1|string2)$)');

并访问如下网址:
-domain/abc/abc 未找到=>不正确 ???
-domain/string1/abc找不到=>正确

and access url like:
- domain/abc/abc not found => incorrect ???
- domain/string1/abc not found => correct

如何解决谢谢

推荐答案

经过测试,我认为无法完全实现所需的功能.似乎当您要排除string1string2时,您需要同意也将排除以string1string2开头的字符串(例如,string1aaa).

After tests I think it's impossible to achieve exactly what you want. It seems when you want to exclude string1 and string2 you need to agree that also strings starting with string1 and string2 will be excluded (so for example string1aaa).

使用此类路线时:

Route::get('/{url1}', function ($url1) {
    return ' url1: '.$url1;
})->where('url1', '(?!string1|string2)[^\/]+');


Route::get('/{url1}/{url2}', function ($url1, $url2) {
    return ' url1: '.$url1. ' # '.$url2;
})->where('url1', '(?!string1|string2)[^\/]+');

结果将是:

domain/abc - found, correct
domain/string1 - not found, correct
domain/abc/abc - found, correct
domain/string1/abc - not found, correct
domain/string1aaa - not found, I believe you need to accept this
domain/string1aaa/abc - not found, I believe you need to accept this

我认为这种限制来自Laravel,而不是来自正则表达式.如果您还需要接受以string1string2开头的参数,我相信您需要像这样手动进行:

I believe such limitation comes from Laravel and not from regex. If you need to accept also parameters starting with string1 and string2 I believe you need to do it in manual way like so:

Route::get('/{url1}', function ($url1) {
    if (!preg_match('#^(?!string1$|string2$)[^\/]*$#', $url1)) {
        abort(404);
    }

    return ' url1: '.$url1;
});


Route::get('/{url1}/{url2}', function ($url1, $url2) {
    if (!preg_match('#^(?!string1$|string2$)[^\/]*$#', $url1)) {
        abort(404);
    }

    return ' url1: '.$url1. ' # '.$url2;
});

这篇关于Laravel-正则表达式路由匹配所有内容,但不完全匹配一个或多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:23