Posted By

a1ias on 03/30/16


Tagged


Versions (?)

Shorten HTML text


 / Published in: PHP
 

URL: https://css-tricks.com/snippets/php/truncate-strings/

Shorten text while preserving the HTML tags. Useful for news and articles preview.

  1. function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
  2. if ( strlen( $input ) >= $limit ) {
  3. $breakpoint = strpos( $input, $break, $limit );
  4. $input = substr( $input, 0, $breakpoint ) . $end_text;
  5. }
  6. if ( $tidy_html == 1 ) {
  7. $tidy = new tidy;
  8. $config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
  9. $tidy->parseString( $input, $config, 'utf8' );
  10. $tidy->cleanRepair( );
  11. $input = $tidy;
  12. }
  13. if ( $strip_html == 1 ) {
  14. $input = strip_tags( $input );
  15. }
  16. return $input;
  17. }

Report this snippet  

You need to login to post a comment.