A fresh mix of code snippets and tutorials

PHP Shorten String by Character Count

Quick copy-n-paste function to truncate or shorten a string of text to a specific number of characters. Useful for things like “next” and “previous” navigation links and so forth.

This function may be used to limit the number of characters for any text input string:

function shapeSpace_truncate_text($text, $max = 50, $append = '…') {
	if (strlen($text) <= $max) return $text;
	$return = substr($text, 0, $max);
	if (strpos($text, ' ') === false) return $return . $append;
	return preg_replace('/\w+$/', '', $return) . $append;

You can specify the following variables:

  • $text – The text string that you want to shorten
  • $max – The maximum number of characters allowed (default = 50)
  • $append – The appended text (default = ellipses)

Once the function is included in your PHP script, you can use it like so:

echo shapeSpace_truncate_text($text, 40);

To specify a custom appended string, you can add a third parameter:

echo shapeSpace_truncate_text($text, 40, ' ..continued..');

or whatever works for you!

Have fun people :)

★ Pro Tip: