preg_match只能匹配一次結果,但很多時候我們需要匹配所有的結果,preg_match_all可以循環獲取一個列表的匹配結果數組。
$p = "|<[^>]+>(.*?)</[^>]+>|i"; $str = "<b>example: </b><div align=left>this is a test</div>"; preg_match_all($p, $str, $matches); print_r($matches);
可以使用preg_match_all匹配一個表格中的數據:
$p = "/<tr><td>(.*?)<\/td>\s*<td>(.*?)<\/td>\s*<\/tr>/i"; $str = "<table> <tr><td>Eric</td><td>25</td></tr> <tr><td>John</td><td>26</td></tr> </table>"; preg_match_all($p, $str, $matches); print_r($matches);
$matches結果排序為$matches[0]保存完整模式的所有匹配, $matches[1] 保存第一個子組的所有匹配,以此類推。
使用preg_match_all匹配所有li標簽中的數據。
在代碼區補充以下代碼:
$p = "/<li>(.*)<\/li>/i";//解釋下這個正則://后面的i表示不區分大小寫,<li>(.*?)<\/li>表示li標簽內的匹配的()內的值有多少,括號內的.表示所有單字符,*表示數量為0個或者多個。也就是li標簽內有字符就顯示出來 preg_match_all($p, $str, $matches); print_r($matches[1]);
請驗證,完成請求
由于請求次數過多,請先驗證,完成再次請求
打開微信掃碼自動綁定
綁定后可得到
使用 Ctrl+D 可將課程添加到書簽
舉報