I try to parse url with a regular expression in order to capture element, but i don’t know how to do. Samples of URL :
- location-cottage with $path_ => array( type => cottage )
- location-cottage-p1 with $path_ => array( type => cottage, page => p1 )
- location-cottage-my-region-r01 with $path_ => array( type => cottage, region => r01 )
- location-cottage-my-department-d01 with $path_ => array( type => cottage, department => d01)
- location-cottage-my-department-d01-p1 with $path_ => array( type => cottage, department => d01, page => p1)
I would like to do this with one regular expression, but i don’t know to do this, i try with this :
$expression = '#location-(?P<type>cottage|house)[a-z,-]*';
$expression.= '(?P<region>r[0-9]{2}|)';
$expression.= '(?P<department>d[0-9]{2}\)';
$expression.= '(?P<town>v[0-9]{5}|)';
$expression.= '[-]*(?P<page>[p0-9]*)$#';
preg_match($expression, $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $path_);
Someone can help me ?
In a second part, if it’s possible I would like to keep only 01 and not d01, only 1 and not p1, as this :
- location-cottage-my-department-d01-p1 with $path_ => array( type => cottage, department => 01, page => 1)
Firstly, use
#xto make your regex more readable. Then use?behind each capture group that can be optional:And if you don’t want to capture the
dfor example, then move it out of the named capture group, and wrap it in(?: )?instead.