kisukedeath

Html cut

Jul 1st, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.23 KB | None | 0 0
  1. function html_cut($text, $max_length)
  2. {
  3.     $tags   = array();
  4.     $result = "";
  5.  
  6.     $is_open   = false;
  7.     $grab_open = false;
  8.     $is_close  = false;
  9.     $in_double_quotes = false;
  10.     $in_single_quotes = false;
  11.     $tag = "";
  12.  
  13.     $i = 0;
  14.     $stripped = 0;
  15.  
  16.     $stripped_text = strip_tags($text);
  17.  
  18.     while ($i < strlen($text) && $stripped < strlen($stripped_text) && $stripped < $max_length)
  19.     {
  20.         $symbol  = $text{$i};
  21.         $result .= $symbol;
  22.  
  23.         switch ($symbol)
  24.         {
  25.            case '<':
  26.                 $is_open   = true;
  27.                 $grab_open = true;
  28.                 break;
  29.  
  30.            case '"':
  31.                if ($in_double_quotes)
  32.                    $in_double_quotes = false;
  33.                else
  34.                    $in_double_quotes = true;
  35.  
  36.             break;
  37.  
  38.             case "'":
  39.               if ($in_single_quotes)
  40.                   $in_single_quotes = false;
  41.               else
  42.                   $in_single_quotes = true;
  43.  
  44.             break;
  45.  
  46.             case '/':
  47.                 if ($is_open && !$in_double_quotes && !$in_single_quotes)
  48.                 {
  49.                     $is_close  = true;
  50.                     $is_open   = false;
  51.                     $grab_open = false;
  52.                 }
  53.  
  54.                 break;
  55.  
  56.             case ' ':
  57.                 if ($is_open)
  58.                     $grab_open = false;
  59.                 else
  60.                     $stripped++;
  61.  
  62.                 break;
  63.  
  64.             case '>':
  65.                 if ($is_open)
  66.                 {
  67.                     $is_open   = false;
  68.                     $grab_open = false;
  69.                     array_push($tags, $tag);
  70.                     $tag = "";
  71.                 }
  72.                 else if ($is_close)
  73.                 {
  74.                     $is_close = false;
  75.                     array_pop($tags);
  76.                     $tag = "";
  77.                 }
  78.  
  79.                 break;
  80.  
  81.             default:
  82.                 if ($grab_open || $is_close)
  83.                     $tag .= $symbol;
  84.  
  85.                 if (!$is_open && !$is_close)
  86.                     $stripped++;
  87.         }
  88.  
  89.         $i++;
  90.     }
  91.  
  92.     while ($tags)
  93.         $result .= "</".array_pop($tags).">";
  94.  
  95.     return $result;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment