2

I have a regex: ^(profile\/\~)(:\([0-9a-z,-]+\))?$ this allows strings like: profile/~ or profile/~:(var1,var2,var3,...)

I need to configure this regex into a Slim route for accept the following routes.

http://example.com/v1/profile/~:(var1, var2)
http://example.com/v1/profile/~:

My PHP code:

$app = new \Slim\App;
$app->group('/v1', function () {
    $this->get('/profile/~[:[{fields:[0-9a-z,-]+}]]', function ($request, $response, $args) {
        $name = $request->getAttribute('name');
        $response->getBody()->write("Hello " . $args['fields']);
        return $response;
    })->setName('profile');
});
$app->run();

Is there any way to convert that regex to one compatible with slim?

Jonathan Nuñez
  • 432
  • 6
  • 19
  • So are we saying you need to restrict the trailing substring pattern to `no parenthetical` and `2 vars in the parenthetical`? – mickmackusa Dec 14 '17 at 07:25
  • Hello, @mickmackusa i need to accept the parenthetical into the Slim Route. – Jonathan Nuñez Dec 14 '17 at 07:28
  • Consider some of the suggestions here: https://stackoverflow.com/questions/39432694/optional-parameters-in-url-slim-3 (I don't use Slim) If you solve your issue, please post your own answer with as much explanation as you can so that future readers can benefit from your research. – mickmackusa Dec 14 '17 at 09:56

1 Answers1

2

I've done a little bit of research, but I am unable to test. Please try the following and give me some feedback regarding what works and what doesn't.

I am unclear about what var1 and var2 are. Are they First Name and Last Name? Are they 2 separate usernames? If they are comma separated, why does your regex permit the vars to contain a comma?

The following method will assume that a non-empty string will be wrapped in parentheses and that the captured string is like "FirstName, LastName" as a single string. (If it is not, then just explode on the comma after trim()ing the parentheses.)

Untested Code: (require a match, but the entire substring is "optional")

$app = new \Slim\App;
$app->group('/v1', function () {
    $this->get('/profile/~:{params:\(?[^,]*,?[^)]*\)?}',function($request,$response,$args){
    //   required capture-^        ^^^-optional()-^^^
        if(strlen($name=$request->getAttribute('params'))){
            $greeting='Hello ',substr($name,1,-1);
        }else{
            $greeting='Hello';
        }
        $response->getBody()->write($greeting);
        return $response;
    })->setName('profile');
});
$app->run();
mickmackusa
  • 43,625
  • 12
  • 83
  • 136