【问题标题】:CakePHP Username URL using Regex?CakePHP 用户名 URL 使用正则表达式?
【发布时间】:2011-08-11 14:44:34
【问题描述】:

我在这里找到了一条评论:http://bakery.cakephp.org/articles/PHPdiddy/2006/10/06/custom-urls-from-the-site-root

也就是说:

只需更改最后一行。
路由器::connect('/', 数组('控制器' => '成员', '动作' => '表演'));

Router::connect('(?!admin|items|images)(.
*)', array('controller' => 'members', 'action' => 'show'));

有些人能够让它工作......虽然它看起来不太对我来说所以我尝试了以下,但仍然没有运气:

Router::connect('(?!/admin|/items|/images)(/.*)',
array('controller' => 'members','action' => 'show'));

在任何情况下,目标都是有一个像 http://domainname/username 这样的 url,映射到用户的唯一 ID。它适用于 /*,但我宁愿不使用该方法。想法?

解决方案更新: 我使用了下面选择的答案并添加了以下内容。它可能对其他人有帮助。

$misc = array(*your misc webroot, admin route items here...*);
$notList = array_merge(Configure::listObjects('plugin'),Configure::listObjects('controller'));
$notListLowerCase = array();
foreach ($notList as $key=>$item):
    $notListLowerCase[] = strtolower(preg_replace("/(.)([A-Z])/","\\1_\\2",$item));
endforeach;
$notList = array_merge($notList,$misc,$notListLowerCase);
$notList = implode('|', $notList);

Router::connect('/:username', 
        array(
            'controller'=>'users', 
            'action'=>'view'
        ),   
        array(
            'username' => '\b(?:(?!'.$notList.')\w)+\b'
        )
    );

【问题讨论】:

    标签: regex cakephp routes friendly-url


    【解决方案1】:

    给你。您需要将其捕获为参数,然后在正则表达式中引用它。用户名将在控制器操作中的 $this->params['username'] 中可用。

    Router::connect('/:username', 
        array(
            'controller'=>'members', 
            'action'=>'show'
        ),   
        array(
            'username' => '\b(?:(?!admin|items|images)\w)+\b'
        )
    );
    

    【讨论】:

    • 谢谢!!它工作得很好。我使用您的解决方案在问题中添加了额外信息,这样您就无需输入所有控制器名称等!
    【解决方案2】:
    $misc = array(*your misc webroot, admin route items here...*);
        $notList = array_merge(App::objects('plugin'),str_replace('Controller','',App::objects('controller')));
        $notListLowerCase = array();
        foreach ($notList as $key=>$item):
            $notListLowerCase[] = strtolower(preg_replace("/(.)([A-Z])/","\\1_\\2",$item));
        endforeach;
        $notList = array_merge($notList,$misc,$notListLowerCase);
        $notList = implode('|', $notList);
        Router::connect('/:username', array('controller' => 'members', 'action' => 'show'),array('pass'=>array('username'),'username'=>'\b(?:(?!'.$notList.')\w)+\b'));
    

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 2011-07-12
      • 2017-10-04
      • 2012-06-04
      相关资源
      最近更新 更多