Home  >  Article  >  Backend Development  >  Use regular expression to detect if tag is closed

Use regular expression to detect if tag is closed

WBOY
WBOYOriginal
2016-07-25 08:46:131219browse
  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. }
Copy code

Explanation:

/]*>/ This pattern is used to match HTML tags (such as:

,
,
, etc., but except
), and holds the name of the tag (such as: head, div) in $start_tags wait). The // pattern is used to match closed HTML tags (such as: ,
, etc.). And keep the closed tag name in $end_tags. Then we use the conditional statement count($start_tags[1]) != count($end_tags[1]) to determine whether the starting tag and the closing tag are equal. If they are not equal, it means they are not closed. Finally, use in_array($start_tags[1][$i], $end_tags[1]) to determine whether the start tag and the closing tag are equal. At this point, we have completed the HTML matching!
Regular expression


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn