Shorten HTML text


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

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.