How to shorten a string to specific number of chars with php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to shorten a string to specific number of chars with php

Post by Saman » Fri Jul 15, 2011 6:36 pm

Function to shorten / truncate a string of text into a specific number of characters and add three dots (...) to the end. This will also round the text to the nearest whole word instead of cutting off part way through a word.

Code: Select all

<?php 
 
/** 
 * Add this to your page: 
 * <?php 
 * include "shorten_a_text_string.php"; 
 * echo ShortenText($text); 
 * ?> 
 * where $text is the text you want to shorten. 
 *  
 * Example 
 * Test it using this in a PHP page: 
 * <?php 
 * include "shortentext.php"; 
 * $text = "The rain in Spain falls mainly on the plain."; 
 * echo ShortenText($text); 
 * ?> 
 */ 
 
    function ShortenText($text) { 
 
        // Change to the number of characters you want to display 
        $chars = 25; 
 
        $text = $text." "; 
        $text = substr($text,0,$chars); 
        $text = substr($text,0,strrpos($text,' ')); 
        $text = $text."..."; 
 
        return $text; 
 
    } 
 
?>
User avatar
Rksk
Major
Major
Posts: 730
Joined: Thu Jan 07, 2010 4:19 pm
Location: Rathnapura, Sri Lanka

Re: How to shorten a string to specific number of chars with php

Post by Rksk » Tue Aug 28, 2012 12:20 am

Just saw this while browsing old topics and I've an improvement for this,

Code: Select all

function ShortenText($text,$chars = 25) { 

  if (strlen($text) <= $chars) return $text; 
  //This prevent adding "...", if string is sorter than $chars.
  
  $text = $text." "; 
  $text = substr($text,0,$chars); 
  $text = substr($text,0,strrpos($text,' ')); 
  $text = $text."..."; 
  return $text; 
 
} 
Post Reply

Return to “PHP & MySQL”