Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created March 1, 2022 18:16
Show Gist options
  • Save wpscholar/20f6b8fcf4326c868ae731e410c38b53 to your computer and use it in GitHub Desktop.
Save wpscholar/20f6b8fcf4326c868ae731e410c38b53 to your computer and use it in GitHub Desktop.
Truncate a string to a certain character length and make sure to only break at words.
<?php
$strings = [
'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve',
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua',
'Bacon ipsum dolor amet burgdoggen biltong pastrami, kielbasa sirloin strip steak cupim andouille tenderloin.',
'Hodor. Hodor hodor, hodor. Hodor hodor hodor hodor hodor. Hodor. Hodor! Hodor hodor, hodor; hodor hodor hodor.',
'Lorem Ipsum is the single greatest threat. We are not - we are not keeping up with other websites.',
'Cupcake ipsum dolor. Sit amet marshmallow topping cheesecake muffin.',
'This test is short.',
'Space, the final frontier. These are the voyages of the Starship Enterprise.'
];
function truncate( $string, $chars = 50 ) {
// If shorter than x characters, skip
if ( strlen( $string ) <= $chars ) {
return $string;
}
// Fetch first x number of characters
$splitByCharacterCount = str_split( $string, $chars );
$truncated = array_shift( $splitByCharacterCount );
// Get array of words after truncation
$words = explode( ' ', $truncated );
// Get array of words before truncation
$originalWords = explode( ' ', $string );
// Get index of last item in array of truncated words
$key = array_key_last( $words );
// If the last word in the array of truncated words has been cut off, drop it from the array
if ( $words[ $key ] !== $originalWords[ $key ] ) {
array_pop( $words );
}
// Convert the array of words back into a string
$newString = implode( ' ', $words );
// Remove any trailing punctuaction
$newString = rtrim( $newString, ',?;:-"\'' );
// Add ellipsis before returning
return $newString . '...';
}
foreach ( $strings as $string ) {
var_dump( truncate( $string, 50 ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment