Last active
April 17, 2018 19:40
-
-
Save eli-oat/7bd229bd76f0f4d770b07740ce9fa540 to your computer and use it in GitHub Desktop.
PHP function to truncate a string to a certain length, and replace overflow with an ellip, makes sure not to truncate mid-word.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function truncate($text, $length = 75, $append = '…') { | |
$length = (int) $length; | |
$text = trim( strip_tags( $text ) ); | |
if ( strlen( $text ) > $length ) { | |
$text = substr( $text, 0, $length + 1 ); | |
$words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY ); | |
preg_match( "/[\s]| /", $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