Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Created June 25, 2019 08:03
Show Gist options
  • Save MaximeCulea/32becdc4a6df08560623554679964ed1 to your computer and use it in GitHub Desktop.
Save MaximeCulea/32becdc4a6df08560623554679964ed1 to your computer and use it in GitHub Desktop.
Trim text
<?php
/**
* Strip then trim a text around the cut $cut_length
*
* @param string $text
* @param int $cut_length
*
* @author Maxime CULEA
*
* @return string
*/
public function trim_text( $text, $cut_length = 70 ) {
// Strips tags and images
$excerpt = strip_tags( strip_shortcodes( $text ) );
// If length bigger than $cut_length, cut it to the closest word and add " ..." characters
if ( $cut_length <= strlen( $excerpt ) ) {
// Add a special word near $cut_length carac's closest word
$excerpt = wordwrap( $excerpt, $cut_length, '*cutme*' );
// Cut into 2 parts with the special word
$excerpt = explode( '*cutme*', $excerpt );
// Reuse only the first part, which means first $cut_length words
$excerpt = sprintf( '%s ...', $excerpt[0] );
}
return $excerpt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment