正则:img的url,width,height 和 a标签的url以及替换

代码:
// 内容:$detail['content'] //img的url,width,height $img = array(); $matches = array(); $regeImg = '/<img.+src="?(.+(jpg|gif|bmp|bnp|png))"?.+width="?(d*)"?.+height="?(d*)"?.+>/i'; if(preg_match_all($regeImg, $detail['content'], $matches)){ //$matches[1] url ;$matches[3] width ;$matches[4] height foreach($matches[1] as $k=>$v){ $img[$k]['ref'] = "<!--IMG#".$k."-->"; $img[$k]['src'] = $v; $img[$k]['alt'] = ''; $img[$k]['width'] = $matches[3][$k]; $img[$k]['height'] = $matches[4][$k]; } } //a标签 $link = array(); $regA= '/<a.*href="(.*)".*>(.*)</isU'; $aList = array(); if(preg_match_all($regA, $detail['content'], $aList)){ //$aList[1] url ;$aList[2] content foreach($aList[1] as $k=>$v){ $link[$k]['ref'] = "<!--link".$k."-->".$aList[2][$k]; $link[$k]['title'] = $aList[2][$k]; $link[$k]['url'] = $v; } } //替换img标签 $str = ""; $regReplaceImg = '/<img.+src="?(.+(jpg|gif|bmp|bnp|png))"?.+width="?(d*)"?.+height="?(d*)"?.+?(?=/)?(>)?/i'; foreach($img as $k=>$v){ if($k == 0){ $content = $detail['content']; $str = $this->replace($regReplaceImg,"<!--IMG#".$k."-->",$content); }else{ $str = $this->replace($regReplaceImg,"<!--IMG#".$k."-->",$str); } } //替换a标签 $body = ''; $regPeplaceA = '/<a.*href="(.*)".*>(.*)</a>/isU'; foreach($link as $k=>$v){ if($k == 0){ $body = $this->replace($regPeplaceA,$v['ref'],$str); }else{ $body = $this->replace($regPeplaceA,$v['ref'],$body); } } //替换 public function replace($reg,$replace,$con){ $str = preg_replace($reg,$replace, $con,1); return $str; }

打印出来的json数据:

  

原文地址:https://www.cnblogs.com/hanybblog/p/6144756.html