复杂的正则表达式来解决

时间:2011-10-29 15:28:30

标签: php regex

我尝试用正则表达式解析url以捕获元素,但我不知道该怎么做。网址示例:

    使用$ path_ =>
  • location-cottage ; array(type => cottage)
  • location-cottage-p1 与$ path_ => array(type => cottage,page => p1)
  • location-cottage-my-region-r01 ,$ path_ => array(type => cottage,region => r01)
  • location-cottage-my-department-d01 ,$ path_ => array(type => cottage,department => d01)
  • location-cottage-my-department-d01-p1 ,$ path_ => array(type => cottage,department => d01,page => p1)

我想用一个正则表达式做这个,但我不知道这样做,我试着用这个:

$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_);

有人可以帮助我吗?

在第二部分中,如果有可能我只想保留01而不是d01,只保留1而不是p1,因为:

  • location-cottage-my-department-d01-p1 ,$ path_ =&gt; array(type =&gt; cottage,department =&gt; 01,page =&gt; 1)

2 个答案:

答案 0 :(得分:3)

首先,使用#x使您的正则表达式更具可读性。然后在每个可选的捕获组后面使用?

$expression = <<< RX 
    #
      location-(?P<type>cottage|house)[a-z,-]*
      (?P<region> r[0-9]{2}|)   ?
      (?P<department> d[0-9]{2})   ?
      (?P<town> v[0-9]{5}|)   ?
      [-]*(?P<page> [p0-9]*)   ?
    $#x
RX;

如果您不想捕获d,例如,请将其移出指定的捕获组,并将其包装在(?: )?中。

答案 1 :(得分:2)

您可以解析字符串

,而不是正则表达式(在大多数情况下都过大)
list($locationString, $type, $region, $department, $town, $page) = array_pad(explode('-', $path(), null, -6);

现在自行验证每个参数(注意,由于null,缺少的参数为array_pad()。这不是更具可读性,但您可以稍后更容易地修改它,例如当您想要添加类型时。