《PHP從字串中截取一部分,支持使用(*)模糊截取》要點:
本文介紹了PHP從字串中截取一部分,支持使用(*)模糊截取,希望對您有用。如果有疑問,可以聯(lián)系我們。
有時會有這種需求,就是從一串代碼或字符中,根據(jù)提供的開始內(nèi)容和結(jié)束內(nèi)容來截取中間部分。
如果開始和結(jié)束內(nèi)容是固定的,很容易操作,這里不詳解。但是如果不是固定的,允許模糊匹配截取,那這里函數(shù)就是用于這種需求。
示例代碼:
$con=<<<END <h2>示例代碼</h2> <div class="pic_show"> <i></i> <img src="http://www.snjht.com/public/images/logo141.png" alt="維易PHP字符串截取函數(shù)"> </div> <div class="detail"> <h1>這是內(nèi)容標(biāo)題</h1> <span style="display:block; height:125px; overflow:hidden;">內(nèi)容部分! 維易PHP函數(shù),可以模糊截取一段文字,隨意的測試代碼,用于測試PHP函數(shù)</span> <div class="count clearfix"> <ul> <li>列表<br><span id="hits"></span></li> <li>PHP函數(shù)</span></li> <li style="border:none;">馬上測試吧</li> </ul> </div> </div> END;
假如要截取h1下面的span一塊,這串代碼中,起點可以用</h1>,但如果結(jié)束部分<div class="count clearfix">,有的是<div class="dd clearfix">有的又是其它,也就是說不固定的,那就要用模糊匹配。
PHP代碼:
$start="<h1>(*)</h1>"; # 或'</h1>' $end=' <div class="(*) clearfix">'; echo extract_BoxSplit ($con, $start, $end);
函數(shù)extract_BoxSplit:
function extract_BoxSplit( $html ,$startStr, $endStr ) { if(stripos ($startStr, '(*)')===false){ $start = stripos ( $html , $startStr); }else{ $starReg = preg_quote ($startStr); $starReg = str_replace ('#','\#',$starReg); $starReg= str_replace ( ['\(\*\)', '(*)'] ,'.*?', $starReg ); preg_match ( "#{$starReg}#is", $html ,$mStart, PREG_OFFSET_CAPTURE, 0 ); $start= !empty($mStart) ? $mStart[0][1] : false; } if($start===false) { $error = '沒有在內(nèi)容中發(fā)現(xiàn)設(shè)置的區(qū)塊起點代碼。'; return false; } $start += (stripos ($startStr, '(*)')!==false && !empty($mStart)) ? strlen ($mStart[0][0]) : strlen( $startStr); if(stripos ($endStr, '(*)')===false){ $end = stripos ( $html , $endStr , $start); }else{ $endReg = preg_quote ($endStr); $endReg = str_replace ('#','\#',$endReg); $endReg= str_replace (['\(\*\)', '(*)'],'.*?', $endReg ); preg_match ( "#{$endReg}#is", $html,$mEnd, PREG_OFFSET_CAPTURE, $start ); $end= !empty($mEnd) ? $mEnd[0][1] : false; } if($end===false) { $error = '沒有在內(nèi)容中發(fā)現(xiàn)設(shè)置的區(qū)塊終點代碼。'; return false; } $str = substr ( $html, $start, $end-$start); return $str; }
提取結(jié)果:
<span style="display:block; height:125px; overflow:hidden;">內(nèi)容部分! 維易PHP函數(shù),可以模糊截取一段文字,隨意的測試代碼,用于測試PHP函數(shù)</span>
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/635.html