Advertisement
Guest User

Untitled

a guest
Jul 7th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.34 KB | None | 0 0
  1.  
  2.     /**
  3.      * Will count number of <[a-z]> tag and </[a-z]> tag (will also validate the order)
  4.      *
  5.      * @source https://stackoverflow.com/a/5723868/1732359
  6.      * @param  string $html
  7.      * @param  boolean $checkOrder
  8.      * @return boolean
  9.      */
  10.     public function isValidHtmlSnippet($html, $checkOrder = true)
  11.     {
  12.         // Add solidus characters to void elements, to prevent them from being matched in the regex that captures start tags.
  13.         $html = preg_replace('#<((?!\/)(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)(.*=".*")[^\/]*)>#i', '<${1} />', $html);
  14.  
  15.         preg_match_all('#<([a-z]+)(?: [a-z]+=".+")?>#i', $html, $start, PREG_OFFSET_CAPTURE);
  16.         preg_match_all('#<\/([a-z]+)>#i', $html, $end, PREG_OFFSET_CAPTURE);
  17.  
  18.         $start = $start[1];
  19.         $end = $end[1];
  20.         if (count($start) != count($end)) {
  21.             throw new Exception('Check numbers of tags');
  22.         }
  23.  
  24.         if (! $checkOrder) {
  25.             return true;
  26.         }
  27.  
  28.         $decrementor = count($start) - 1;
  29.         foreach ($end as $v) {
  30.  
  31.             if ($v[0] != $start[$decrementor][0] || $v[1] < $start[$decrementor][1]) {
  32.                 throw new Exception('End tag [' . $v[0] . '] not opened');
  33.             }
  34.  
  35.             $decrementor--;
  36.         }
  37.        
  38.         return true;
  39.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement