使用Regex來檢測標籤是否關閉

來源:互聯網
上載者:User
  1. function check_html($html) {
  2. preg_match_all("/<([a-zA-Z0-9]+)\\s*[^\\/>]*>/",$html,$start_tags);
  3. preg_match_all("/<\\/([a-zA-Z0-9]+)>/", $html, $end_tags);
  4. if(count($start_tags[1]) != count($end_tags[1])) return false;
  5. for($i = 0; $i < count($start_tags[1]); $i++) {
  6. if(!in_array($start_tags[1][$i], $end_tags[1])) return false;
  7. }
  8. return true;
  9. }
複製代碼

解釋:

/<([a-zA-Z0-9]+)\\s*[^\\/>]*>/這個模式是用來匹配HTML的標記(如:、、等等,但是除了
這種)的,並且在$start_tags保持著標籤的名字(如:head、div等)。而/<\\/([a-zA-Z0-9]+)>/這個模式是用來匹配閉合的HTML標記(如:,等)的。並且在$end_tags中保持這閉合的標籤名。然後我們用count($start_tags[1]) != count($end_tags[1])這個條件陳述式來判斷開始的標記跟閉合的標記是否相等,不相等就說明沒閉合。最後用in_array($start_tags[1][$i], $end_tags[1])來判斷開始標跟閉合的標記是否相等。至此,我們就完成了HTML的匹配了!

Regex
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.