Heim >Backend-Entwicklung >PHP-Tutorial >遇到正则难题,请高手指点
大家好,我正在做正则匹配,想把以下属性名称(如颜色分类和套餐类型)和属性值(白色,黑色,套餐一,套餐二,套餐三)抽取出来,我的做法是先把每个
//自己到网上下一个include('simple_html_dom.php');$dom=new simple_html_dom();$dom->load($s);//$s 就是你的html$dls=$dom->find('dl');$res=array();foreach($dls as $k=>$dl){ $res[$k]['type']=$dl->find('dt')[0]->text(); foreach($dl->find('li') as $k1=>$li){ $res[$k][] = $li->find('span')[0]->text(); }}echo "<pre class="brush:php;toolbar:false">";print_r($res);echo "";/*Array( [0] => Array ( [type] => 颜色分类 [0] => 白色 [1] => 黑色 ) [1] => Array ( [type] => 套餐类型 [0] => 套餐一 [1] => 套餐二 [2] => 套餐三 ))*/
$s =<<< HTML<dl class="J_Prop tb-prop tb-clear J_Prop_Color "> <dt class="tb-property-type">颜色分类</dt> <dd> <ul data-property="颜色分类" class="J_TSaleProp tb-img tb-clearfix"> <li data-value="1627207:3232483" class="tb-txt"> <a href="javascript:void(0);"> <span>白色</span> </a> <i>已选中</i> </li> <li data-value="1627207:28327" class="tb-txt"> <a href="javascript:void(0);"> <span>黑色</span> </a> <i>已选中</i> </li> </ul> </dd></dl> <dl class="J_Prop tb-prop tb-clear "> <dt class="tb-property-type">套餐类型</dt> <dd> <ul data-property="套餐类型" class="J_TSaleProp tb-clearfix"> <li data-value="5919063:3266781"> <a href="javascript:void(0);"> <span>套餐一</span> </a> <i>已选中</i> </li> <li data-value="5919063:3266779"> <a href="javascript:void(0);"> <span>套餐二</span> </a> <i>已选中</i> </li> <li data-value="5919063:3266785"> <a href="javascript:void(0);"> <span>套餐三</span> </a> <i>已选中</i> </li> </ul> </dd></dl> HTML;preg_match_all('#<dl class="J_Prop tb-prop tb-clear.*?>(.+?)</dl>#is', $s, $m);foreach($m[1] as $i=>$v) { preg_match_all('#<(dt|span).*>(.+)</\1>#isU', $v, $m); $r[$i] = $m[2];}print_r($r);
Array( [0] => Array ( [0] => 颜色分类 [1] => 白色 [2] => 黑色 ) [1] => Array ( [0] => 套餐类型 [1] => 套餐一 [2] => 套餐二 [3] => 套餐三 ))