close tags in a html-snippet


/ Published in: PHP
Save to your folder(s)

suppose you have some html-formatted text of which you would like to show the first 45 characters.
This function closes any tags that are not-closed because of cutting the first 45 characters.

Note that tags are also counted when defining the first 45 characters!


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function closetags ( $html )
  4. {
  5. #put all opened tags into an array
  6. preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
  7. $openedtags = $result[1];
  8.  
  9. #put all closed tags into an array
  10. preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
  11. $closedtags = $result[1];
  12. $len_opened = count ( $openedtags );
  13. # all tags are closed
  14. if( count ( $closedtags ) == $len_opened )
  15. {
  16. return $html;
  17. }
  18. $openedtags = array_reverse ( $openedtags );
  19. # close tags
  20. for( $i = 0; $i < $len_opened; $i++ )
  21. {
  22. if ( !in_array ( $openedtags[$i], $closedtags ) )
  23. {
  24. $html .= "</" . $openedtags[$i] . ">";
  25. }
  26. else
  27. {
  28. unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
  29. }
  30. }
  31. return $html;
  32. }
  33.  
  34. $str = "<div>This is some interesting <strong><em>content!</em> And this</strong> line is <em>";
  35. $str .= "abundantly</em> formatted</div>";
  36.  
  37. $snippet = substr ( $str, 0, 45 );
  38.  
  39. $snippet = strrpos ( $snippet, "<" ) > strrpos ( $snippet, ">" ) ? rtrim ( substr ( $str, 0, strrpos ( $snippet, "<" ) ) ) . "....." : rtrim ( $snippet ) . ".....";
  40.  
  41. $x = closetags ( $snippet );
  42.  
  43. print htmlspecialchars ( $x );
  44.  
  45. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.