Taie cod HTML fara sa strici tagurile HTML

In cadrul unui proiect recent a trebuit sa dezvolt o functie care sa ia sursa HTMl a unei pagini si sa o sparga in mai multe parti, fara ca sa taie in mijlocul unui tag HTML. Dupa ce m-am chinuit o perioada sa scriu acest cod am decis sa apelez la coderi mai inspirati si sa caut pe google o solutie :D . Dupa o vreme de cautat si incercat diverse coduri am dat de codul de mai jos. Este o metoda dintr-o clasa a cakephp framework si isi face treaba perfect.

Sper sa aveti noroc si daca cautati acesta functie sa gasiti acest articol si sa salvati niste timp.
Cheers

PHP:
  1. /**
  2. * Truncates text.
  3. *
  4. * Cuts a string to the length of $length and replaces the last characters
  5. * with the ending if the text is longer than length.
  6. *
  7. * @param string  $text String to truncate.
  8. * @param integer $length Length of returned string, including ellipsis.
  9. * @param string  $ending Ending to be appended to the trimmed string.
  10. * @param boolean $exact If false, $text will not be cut mid-word
  11. * @param boolean $considerHtml If true, HTML tags would be handled correctly
  12. * @return string Trimmed string.
  13. */
  14.     function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
  15.         if ($considerHtml) {
  16.             // if the plain text is shorter than the maximum length, return the whole text
  17.             if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  18.                 return $text;
  19.             }
  20.             // splits all html-tags to scanable lines
  21.             preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  22.             $total_length = strlen($ending);
  23.             $open_tags = array();
  24.             $truncate = '';
  25.             foreach ($lines as $line_matchings) {
  26.                 // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  27.                 if (!empty($line_matchings[1])) {
  28.                     // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
  29.                     if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  30.                         // do nothing
  31.                     // if tag is a closing tag (f.e. </b>)
  32.                     } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  33.                         // delete tag from $open_tags list
  34.                         $pos = array_search($tag_matchings[1], $open_tags);
  35.                         if ($pos !== false) {
  36.                             unset($open_tags[$pos]);
  37.                         }
  38.                     // if tag is an opening tag (f.e. <b>)
  39.                     } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  40.                         // add tag to the beginning of $open_tags list
  41.                         array_unshift($open_tags, strtolower($tag_matchings[1]));
  42.                     }
  43.                     // add html-tag to $truncate'd text
  44.                     $truncate .= $line_matchings[1];
  45.                 }
  46.                 // calculate the length of the plain text part of the line; handle entities as one character
  47.                 $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  48.                 if ($total_length+$content_length> $length) {
  49.                     // the number of characters which are left
  50.                     $left = $length - $total_length;
  51.                     $entities_length = 0;
  52.                     // search for html entities
  53.                     if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  54.                         // calculate the real length of all entities in the legal range
  55.                         foreach ($entities[0] as $entity) {
  56.                             if ($entity[1]+1-$entities_length <= $left) {
  57.                                 $left--;
  58.                                 $entities_length += strlen($entity[0]);
  59.                             } else {
  60.                                 // no more characters left
  61.                                 break;
  62.                             }
  63.                         }
  64.                     }
  65.                     $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
  66.                     // maximum lenght is reached, so get off the loop
  67.                     break;
  68.                 } else {
  69.                     $truncate .= $line_matchings[2];
  70.                     $total_length += $content_length;
  71.                 }
  72.                 // if the maximum length is reached, get off the loop
  73.                 if($total_length>= $length) {
  74.                     break;
  75.                 }
  76.             }
  77.         } else {
  78.             if (strlen($text) <= $length) {
  79.                 return $text;
  80.             } else {
  81.                 $truncate = substr($text, 0, $length - strlen($ending));
  82.             }
  83.         }
  84.         // if the words shouldn't be cut in the middle...
  85.         if (!$exact) {
  86.             // ...search the last occurance of a space...
  87.             $spacepos = strrpos($truncate, ' ');
  88.             if (isset($spacepos)) {
  89.                 // ...and cut the text in this position
  90.                 $truncate = substr($truncate, 0, $spacepos);
  91.             }
  92.         }
  93.         // add the defined ending to the text
  94.         $truncate .= $ending;
  95.         if($considerHtml) {
  96.             // close all unclosed html-tags
  97.             foreach ($open_tags as $tag) {
  98.                 $truncate .= '</' . $tag . '>';
  99.             }
  100.         }
  101.         return $truncate;
  102.     }

Articole similare

blog comments powered by Disqus