Question

this is the function i have in my template for word trim

<?php


/**
* Trim a string to a given number of words
*
* @param $string
*   the original string
* @param $count
*   the word count
* @param $ellipsis
*   TRUE to add "..."
*   or use a string to define other character
* @param $node
*   provide the node and we'll set the $node->
*
* @return
*   trimmed string with ellipsis added if it was truncated
*/

   function word_trim($string, $count, $ellipsis = FALSE){
$words = explode(' ', $string);
if (count($words) > $count){
    array_splice($words, $count);
    $string = implode(' ', $words);

    if (is_string($ellipsis)){
        $string .= $ellipsis;
    }
    elseif ($ellipsis){
        $string .= '&hellip;';
    }
}
return $string;
}

?>

and in the page itself it looks like this

<?php echo word_trim(get_the_excerpt(), 12, ''); ?>

I was wondering, is there a way I could modify that function to trim the number of characters instead of the number of words? because sometimes when there are longer words it all gets offset and unaligned.

Thank you

Was it helpful?

Solution

Take a look at the logic of the function: It splits the string by a space, counts and slices the resulting array and puts them back together.
Now a space is a delimiter for words... on what char do we need to split the string to get all characters instead of words? Right, on nothing (better to say: an empty string)!

So you change both of these lines

function word_trim($string, $count, $ellipsis = FALSE){
  $words = explode(' ', $string);
  if (count($words) > $count){
    //...
    $string = implode(' ', $words);
  }
  //...
}

to

$words = str_split($string);
//...
$string = implode('', $words);

and you should be fine.
Note that i changed the first explode-call to str_split, as explode doesn't accept an empty delimiter (according to the manual).

I'd rename the function to character_trim or something else and perhaps the $word variable, too, so your code will make sense to a reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top