Skip to content

Instantly share code, notes, and snippets.

@eli-oat eli-oat/truncate.php
Last active Apr 17, 2018

Embed
What would you like to do?
PHP function to truncate a string to a certain length, and replace overflow with an ellip, makes sure not to truncate mid-word.
<?php
function truncate($text, $length = 75, $append = '&hellip;') {
$length = (int) $length;
$text = trim( strip_tags( $text ) );
if ( strlen( $text ) > $length ) {
$text = substr( $text, 0, $length + 1 );
$words = preg_split( "/[\s]|&nbsp;/", $text, -1, PREG_SPLIT_NO_EMPTY );
preg_match( "/[\s]|&nbsp;/", $text, $lastchar, 0, $length );
if ( empty( $lastchar ) )
array_pop( $words );
$text = implode( ' ', $words ) . $append;
}
return $text;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.