Search code examples
phpregexyiiyii-url-manager

Changing pattern of url to accept username like facebook


I need to covert user profile link from this http://example.com/site/index?user_id=sami.yaqoub

To be like Facebook http://example.com/sami.yaqoub

I changed the rules of config file to except that.

Config.php

<?php
..
 'urlManager' => array(
            'urlFormat' => 'path',
            'showScriptName' => false,
            'rules' => array(
                    '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                '<user:[a-zA-Z0-9_-]\w+>'=>'site/index',// here is the code 
            ),
        ),
...
?>

It worked with all words not contained any dot "." , so I changed it to be like this

 '<user:[a-zA-Z0-9_-.]\w+>'=>'site/index',// return error

But also not worked . What is the best method in this case to except this formula Name.anything

Thanks in advance


Solution

  • In you regexp [a-zA-Z0-9_-.]\w+ you can match things like .helloworld but not hello.world because you match the dot . character only in first position.

    You should write it like that : [a-zA-Z0-9_-.][\w.]+.

    I am not sure, but maybe Facebook does not allow special characters in first position such as dot or dash.-. In that case the correct answer would be : [a-zA-Z0-9][\w.]+ or shorter \w[\w.]+

    Note that \w in a regexp matches word characters. \w is equivalent to [A-Za-z0-9_]