Advertisement
Stann

Semantic HTML

Sep 3rd, 2014
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.94 KB | None | 0 0
  1. <?php
  2. $html = $_GET['html'];
  3. $lines = preg_split('/[\n]/', $html, -1, PREG_SPLIT_NO_EMPTY);
  4.  
  5. foreach ($lines as $key => $value) {
  6.     if (strpos($value, 'div') !== false) {
  7.         //extract div
  8.         preg_match_all('/<div[^>]*>/', $value, $matches);
  9.         if (count($matches[0]) > 0) {
  10.             $div = $matches[0][0];
  11.             //extract id and class attributes
  12.             preg_match_all('/(id\s*=\s*"[^"]+")|(class\s*=\s*"[^"]+")/', $div, $matches2);
  13.             $atr = $matches2[0][0];
  14.             //exact tag name
  15.             preg_match_all('/"[^"]+"/', $atr, $matches3);
  16.             $tag = $matches3[0][0];
  17.             //remove quotes from tag name
  18.             $tag = preg_replace('/"/', '', $tag);
  19.             //replace div with tag name
  20.             $lines[$key] = preg_replace('/div/', $tag, $value);
  21.             //remove id and class
  22.             $lines[$key] = preg_replace('/(id\s*=\s*"[^"]+"\s*)|(class\s*=\s*"[^"]+"\s*)/', '', $lines[$key]);
  23.             //clear excessive spaces at the end
  24.             $lines[$key] = preg_replace('/\s*>/', '>', $lines[$key]);
  25.             //make multiple spaces single
  26.             $lines[$key] = preg_replace('/\s{2,}/', ' ', $lines[$key]);
  27.         } else {
  28.             //extract /div
  29.             preg_match_all('/<\/div>\s*<!--\s*[^--]*-->/', $value, $matches);
  30.             $div = $matches[0][0];
  31.             //extract tag name from comment
  32.             preg_match_all('/(\s*(nav)\s*)|(\s*(main)\s*)|(\s*(header)\s*)|(\s*(section)\s*)|(\s*(article)\s*)|(\s*(aside)\s*)|(\s*(footer)\s*)/', $div, $matches2);
  33.  
  34.             $tag = trim($matches2[0][0]);
  35.             //replace /div with tag name
  36.             $lines[$key] = preg_replace('/div/', $tag, $value);
  37.             //remove comment tag
  38.             $lines[$key] = preg_replace('/<!--\s*[^-]*-->/', '', $lines[$key]);
  39.         }
  40.     } else {
  41.         continue;
  42.     }
  43. }
  44. $result = implode("\n", $lines);
  45. echo $result;
  46. //var_dump($lines);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement