1 Replies - 1780 Views - Last Post: 12 September 2012 - 04:36 PM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Truncate text (such as blog post)

Posted 01 May 2009 - 08:29 AM

Description: Provide the text you wish to have truncated, the length you want (defaults to 75 characters( and the trailing characters (default is the ellipse (...)This is a snippet for truncating text (such as with a blog post) and add trailing ellipses. Useful for long blog posts, and can add a "Read More" link
/*   
** Function for truncating text and adding trailing characters
** default characters is the ellipse (...) but can be whatever the
** user chooses. The default length is 75 characters but the
** user can change that as well. The function has 3 parameters:
**
** $textToTruncate - The text we wish to truncate 
** $truncLen - Maximum length we want the text to be  
** $truncateChars - characters to append to end of truncated text
				  (default is the ellipse)
*/   

function truncateText($textToTruncate, $maxLength = 75, $trailingChars='...')   
{
	//subtract the length of the ellipses from the max length value
	$maxLength -= mb_strlen($trailingChars);  
	
	//check to see if the text provided is longer than the maximum length
	if (mb_strlen($textToTruncate)> $maxLength)  
	{  
	   //Since we're here then the text is longer than
	   //the maximum length we wish to allow so we need
	   //to truncate the text and add the truncate characters
	   return mb_substr($textToTruncate,0,$maxLength).$trailingChars;  
	}  
	else  
	{
	   // string was already short enough, return the string  
	   $truncatedText = $textToTruncate;  
	}

	//return the truncated text
	return $truncatedText;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Truncate text (such as blog post)

#2 draven_caine   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 12-September 12

Re: Truncate text (such as blog post)

Posted 12 September 2012 - 04:36 PM

Thanks for posting this, it helped alot for needing to truncate a foreach command.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1