Trimming a block of text to the nearest word when a certain character limit is reached?

前端 未结 6 1094
甜味超标
甜味超标 2020-12-12 05:08

Here is the question: How would your trim a block of text to the nearest word when a certain amount of characters have past. I\'m not trying to limit a certain number words

相关标签:
6条回答
  • 2020-12-12 05:40

    See the wordwrap function.

    I would probably do something like:

    function wrap($string) {
      $wstring = explode("\n", wordwrap($string, 27, "\n") );
      return $wstring[0];
    }
    

    (If your strings already span across severeal lines, use other char - or pattern - for the split other than "\n")

    0 讨论(0)
  • 2020-12-12 05:41

    You can use a little-known modifier to str_word_count to help do this. If you pass the parameter '2', it returns an array of where the word position are.

    The following is a simple way of using this, but it might be possible to do it more efficiently:

    $str = 'This is a string with a few words in';
    $limit = 20;
    $ending = $limit;
    
    $words = str_word_count($str, 2);
    
    foreach($words as $pos=>$word) {
        if($pos+strlen($word)<$limit) {
            $ending=$pos+strlen($word);
        }
        else{
            break;
        }
    }
    
    echo substr($str, 0, $ending);
    // outputs 'this is a string'
    
    0 讨论(0)
  • 2020-12-12 05:41
    // Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
    if(strlen($very_long_text) > 120) {
      $matches = array();
      preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
      $trimmed_text = $matches[0]. '...';
    }
    
    0 讨论(0)
  • 2020-12-12 05:51

    I think this should do the trick:

    function trimToWord($string, $length, $delimiter = '...')
    {
        $string        = str_replace("\n","",$string);
        $string        = str_replace("\r","",$string);
        $string        = strip_tags($string);
        $currentLength = strlen($string);
    
        if($currentLength > $length)
        {
            preg_match('/(.{' . $length . '}.*?)\b/', $string, $matches);
    
            return rtrim($matches[1]) . $delimiter;
        }
        else 
        {
            return $string;
        }
    }
    
    0 讨论(0)
  • 2020-12-12 05:56

    I wrote a max-string-length function that does just this and is very clean.

    0 讨论(0)
  • 2020-12-12 05:59

    Wouldn't it be simpler to concat the strings using a place holder (i.e.: ###PLACEHOLDER###), count the chars of the string minus your place holder, trim it to the right length with substr and then explode by placeholder?

    0 讨论(0)
提交回复
热议问题