为url段上传递的参数定义一个模式


Define a pattern for paramenters passed on url segment on codeigniter

我找到了一种方法来定义一个模式,在codeigniter上传递url参数…我指的是像这样的模式:

www.example.com/part/of/url/parameter1/parameter2

我需要传递一个mac,所以模式必须与XX-XX-XX-XX-XX-XX - xx 一致,否则,框架会发送404。
正如我所说,我找到了一种方法来制作这个,但我不知道这是否是最好的方法。我所做的是修改一个文件在系统文件夹…特别是在文件:system/core/Router.php中,我将默认的第379行更改为另一行:

 $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', str_replace(':mac', '[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}', $key)));

它是……但我想知道是否有任何方法,我不需要修改系统文件夹上的文件…我已经明白这不是一个好主意。

谢谢。

可以在config/routes.php

例如:

$route['part/of/url/parameter1/([0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2})'] = 'my/routed/$1';

它只会路由与你的模式匹配的url。参见http://www.codeigniter.com/user_guide/general/routing.html正则表达式

一节

或者,您可以在routes.php的末尾执行此操作。

$route['part/of/url/parameter1/(:mac)'] = 'my/routed/$1';

$temp = [];
foreach($route as $key => $value)
{
 $key = str_replace(':mac', '[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}', $key);
 $temp[$key] = $value;
}
$route = $temp;

保持一个干净的代码,这是很好的把这部分放在hooks,看看https://ellislab.com/codeigniter/user-guide/general/hooks.html

保持system文件的完整是非常重要的,因为您将来会想要更新codeigniter。

就是另一种方式:

// my rules
$mac = '[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}';
$route["part/of/url/parameter1/($mac)"] = 'my/routed/$1';