PHP Shorten (Truncate) Text / Strings

///PHP Shorten (Truncate) Text / Strings

PHP Shorten (Truncate) Text / Strings

Just a simple function to take any given string and just shorten it. Sometimes you have an column in your DB thats a few paragraphs long but the page you want to display a snippet of the column only has room for 50 characters (or however many you can spare).\r\n\r\nAn example would be:\r\n\r\nOriginal:\r\nThis would represent a larger amount of text that I want to shorten to lets say 30 characters due to property or element on my page being limited in size.\r\n\r\nShortened:\r\n $chars)\r\n {\r\n $text = substr($text,0,$chars);\r\n $text = substr($text,0,strrpos($text,’ ‘));\r\n $text = $text.”…”;\r\n }\r\n return $text;\r\n}\r\n?>\r\n\r\n\r\n\r\nCode:\r\n
\r\nfunction ShortenText($text, $chars)\r\n{\r\n	$chars = $chars;$text = $text." ";\r\n	$countchars = strlen($text);\r\n	if($countchars > $chars)\r\n	{\r\n		$text = substr($text,0,$chars);\r\n		$text = substr($text,0,strrpos($text,' '));\r\n		$text = $text."...";\r\n	}\r\n	return $text;\r\n}\r\necho ShortenText($fullText, 30);\r\n
By | 2014-01-05T10:25:33+00:00 March 8th, 2012|Code, PHP|0 Comments

About the Author:

Not much to know about me, I'm a 35+ year old coder, geek, gamer..

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: