Created
March 1, 2022 18:16
-
-
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.
This file contains hidden or 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 | |
$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