PHP Shorten String by Character Count

来源:互联网 时间:1970-01-01

PHP

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:

PHP truncate string to any number of characters

PHP

function shapeSpace_truncate_text($text, $max = 50, $append = '&hellip;') {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 :)

相关阅读:
Top