Reputation: 31
I need some help with a PHP based path parser, I am trying to create a path router that grabs arguments form the given string and returns an keyed array containing the results. I can do it inside of a whole loop where each area is broken down and tested seperatly but I feel that there should be a way to do it as a signaler regex that then loops though the results
users/<id:(\d+)>/ = users/1 || users/42 != users/bob
returns args['id'] = 1 || args['id'] = 42
user/register
args = []
name/<fname:([a-zA-Z]{1,10})>/<lname:([a-zA-Z]{1,10})> = name/bob/smith || name/jordan/freeman
args['fname'] = bob || args['fname'] = jordan
args['lname'] = smith || args['lname'] = freeman
Upvotes: 0
Views: 78
Reputation: 31
Named captures is what I was looking for, just need to transform my markup or redo the patterning. http://www.regular-expressions.info/named.html
Here is what I can up with, IDK if it will help anyone else?
$str = 'user/1/';
$reg = "user\/(?P<ID>\d+)\/";
var_dump(testPath($str, $reg));
$str = 'user/bob/smith/';
$reg = "user\/(?P<fname>[a-zA-Z]+)\/(?P<lname>[a-zA-Z]+)\/";
var_dump(testPath($str, $reg));
function testURL($url, $reg){
if(preg_match("/^$reg$/", $url, $matches)){
return $matches;
}else{
return null;
}
}
Upvotes: 1