WordPress Code Snippets

A fresh mix of code snippets and tutorials

PHP Shorten String by Character Count

233

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:

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 :)


Show Support

Like our new Facebook Page to show support!