Skip to content

Instantly share code, notes, and snippets.

@maugelves
Last active November 2, 2016 10:02
Show Gist options
  • Save maugelves/a7b685ab9ac6c4fab0c1d95d4b4575fb to your computer and use it in GitHub Desktop.
Save maugelves/a7b685ab9ac6c4fab0c1d95d4b4575fb to your computer and use it in GitHub Desktop.
Crop a text to a specific word count.
<?php
/**
* Crop a text to a specific word count
*
* @author Mauricio Gelves <yo@maugelves.com>
* @param $text_to_trim string
* @param $wordcount int
* @param $final string Which string do you want to add at the final of the trimmed text?
* @return string
*/
function text_cropper($text_to_trim, $wordcount, $final = '…') {
// Check parameters
if( empty( $text_to_trim ) || empty( $wordcount ) || !is_numeric( $wordcount ) ) return false;
// Variables
$trimed = '';
$text = str_replace(" ", " ", $text_to_trim);
$string = explode(" ", $text);
// Check the text has more words than the required
if( count($string) <= $wordcount ) return $text_to_trim;
for ( $wordCounter = 0; $wordCounter < $wordcount; $wordCounter++ ){
$trimed .= $string[$wordCounter];
if ( $wordCounter + 1 < $wordcount ){ $trimed .= " "; }
}
$trimed .= $final;
return $trimed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment