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

Use regular expression to detect if tag is closed

WBOY
Release: 2016-07-25 08:46:13
Original
1250 people have browsed it
  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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template