Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Will count number of <[a-z]> tag and </[a-z]> tag (will also validate the order)
- *
- * @source https://stackoverflow.com/a/5723868/1732359
- * @param string $html
- * @param boolean $checkOrder
- * @return boolean
- */
- public function isValidHtmlSnippet($html, $checkOrder = true)
- {
- // Add solidus characters to void elements, to prevent them from being matched in the regex that captures start tags.
- $html = preg_replace('#<((?!\/)(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)(.*=".*")[^\/]*)>#i', '<${1} />', $html);
- preg_match_all('#<([a-z]+)(?: [a-z]+=".+")?>#i', $html, $start, PREG_OFFSET_CAPTURE);
- preg_match_all('#<\/([a-z]+)>#i', $html, $end, PREG_OFFSET_CAPTURE);
- $start = $start[1];
- $end = $end[1];
- if (count($start) != count($end)) {
- throw new Exception('Check numbers of tags');
- }
- if (! $checkOrder) {
- return true;
- }
- $decrementor = count($start) - 1;
- foreach ($end as $v) {
- if ($v[0] != $start[$decrementor][0] || $v[1] < $start[$decrementor][1]) {
- throw new Exception('End tag [' . $v[0] . '] not opened');
- }
- $decrementor--;
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement