Truncate String by Words

Technique #1

<?php
function trunc($phrase, $max_words) {
   $phrase_array = explode(' ',$phrase);
   if(count($phrase_array) > $max_words && $max_words > 0)
      $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';
   return $phrase;
}
?>

Technique #2

function limit_words($words, $limit, $append = ' &hellip;') {
       // Add 1 to the specified limit becuase arrays start at 0
       $limit = $limit+1;
       // Store each individual word as an array element
       // Up to the limit
       $words = explode(' ', $words, $limit);
       // Shorten the array by 1 because that final element will be the sum of all the words after the limit
       array_pop($words);
       // Implode the array for output, and append an ellipse
       $words = implode(' ', $words) . $append;
       // Return the result
       return $words;
}

Comments

  1. User Avatar
    Xevo
    Permalink to comment#

    Which is better on a high traffic site?

  2. User Avatar
    Eddy Erkelens
    Permalink to comment#

    Instead only words, this works for sentences.
    So no half sentences anymore:

    <?php
    
    function substr_sentence($string, $start=0, $limit=10, $max_char = 300)
        {
        /* This functions cuts a long string in sentences.
        *
        * substr_sentence($string, $start, $limit);
        * $string = 'A example. By someone that loves PHP. Do you? We do!';
        * $start = 0; // we would start at the beginning
        * $limit = 10; // so, we get 10 sentences (not 10 words or characters!)
        *
        * It's not as substr()) in single characters.
        * It's not as substr_words() in single words.
        * 
        * No more broken lines in a story. The story/article must go on!
        *
        * Written by Eddy Erkelens "Zunflappie"
        * Published on www.mastercode.nl 
        * May be free used and adapted
        *
        */
        
        // list of sentences-ends. All sentences ends with one of these. For PHP, add the ;
        $end_characters = array(
                    '.', 
                    '?',
                    '!'
                    );
        
        // put $string in array $parts, necessary evil
        $parts = array($string);            
            
        // foreach interpunctation-mark we will do this loop
        foreach($end_characters as $end_character)
            {
            // go thru each part of the sentences we already have
            foreach($parts as $part)
                {
                // make array with the new sentences
                $sentences[] = explode($end_character, $part);
                }
            
            // unfortunately explode() removes the end character itself. So, place it back
            foreach($sentences as $sentence)
                {
                // some strange stuff
                foreach($sentence as $real_sentence)
                    {
                    // empty sentence we do not want
                    if($real_sentence != '')
                        {
                        // if there is already an end-character, dont place another one
                        if(in_array(substr($real_sentence, -1, 1), $end_characters))
                            {
                            // store for next round
                            $next[] = trim($real_sentence);        
                            }
                        else
                            {
                            // store for next round
                            $next[] = trim($real_sentence).$end_character;    
                            }
                        }
                    }
                }
                
            // store for next round
            $parts = $next;
            
            // unset the remaining and useless stuff
            unset($sentences, $sentence, $next);
            }    
    
        // check for max-char-length
        $total_chars = 0;
        $sentence_nr = 0;
        $sentences = array();
        
        // walk thru each member of $part
        foreach($parts as $part)
            {
            // count the string-lenght and add this to $total_chars
            $total_chars += strlen($part);
            
            // if $total-chars is higher then max-char, dont add this sentences!
            if($total_chars 
    • User Avatar
      dB
      Permalink to comment#

      @ Eddy Erkelens. Your solution is really interesting. Could you post the full code of the function because it got cut on the part if($total_chars…

  3. User Avatar
    Eddy Erkelens
    Permalink to comment#

    Here is it:
    A little bit late, but i did need the function again, for myself

    <?php

    function substr_sentence($string, $start=0, $limit=10, $max_char = 600)
    {
    /* This functions cuts a long string in sentences.
    *
    * substr_sentence($string, $start, $limit);
    * $string = 'A example. By someone that loves PHP. Do you? We do!';
    * $start = 0; // we would start at the beginning
    * $limit = 10; // so, we get 10 sentences (not 10 words or characters!)
    *
    * It's not as substr()) in single characters.
    * It's not as substr_words() in single words.
    *
    * No more broken lines in a story. The story/article must go on!
    *
    * Written by Eddy Erkelens "Zunflappie"
    * Published on http://www.mastercode.nl
    * May be free used and adapted
    *
    */

    // list of sentences-ends. All sentences ends with one of these. For PHP, add the ;
    $end_characters = array(
                '. ', 
                '? ',
                '! '
                );
    
    // put $string in array $parts, necessary evil
    $parts = array($string);            
    
    // foreach interpunctation-mark we will do this loop
    foreach($end_characters as $end_character)
        {
        // go thru each part of the sentences we already have
        foreach($parts as $part)
            {
            // make array with the new sentences
            $sentences[] = explode($end_character, $part);
            }
    
        // unfortunately explode() removes the end character itself. So, place it back
        foreach($sentences as $sentence)
            {
            // some strange stuff
            foreach($sentence as $real_sentence)
                {
                // empty sentence we do not want
                if($real_sentence != '')
                    {
                    // if there is already an end-character, dont place another one
                    if(in_array(substr($real_sentence, -1, 1), $end_characters))
                        {
                        // store for next round
                        $next[] = trim($real_sentence);        
                        }
                    else
                        {
                        // store for next round and add the removed character
                        $next[] = trim($real_sentence).$end_character;    
                        }
                    }
                }
            }
    
        // store for next round
        $parts = $next;
    
        // unset the remaining and useless stuff
        unset($sentences, $sentence, $next);
        }    
    
    // check for max-char-length
    $total_chars = 0;
    $sentence_nr = 0;
    $sentences = array();
    
    // walk thru each member of $part
    foreach($parts as $part)
        {
        // count the string-lenght and add this to $total_chars
        $total_chars += strlen($part);
    
        // if $total-chars not already higher then max-char, add this sentences!
        if($total_chars 
    

  4. User Avatar
    Eddy Erkelens
    Permalink to comment#

    And the last part… apart.


    // walk thru each member of $part
    foreach($parts as $part)
    {
    // count the string-lenght and add this to $total_chars
    $total_chars += strlen($part);

        // if $total-chars not already higher then max-char, add this sentences!
        if($total_chars 
    

  5. User Avatar
    Eddy Erkelens
    Permalink to comment#

    Bloody bug…

    It get cuts of on a ARROW_LEFT..

    So: codepad to the rescue. Sorry Chris.
    Link: http://codepad.org/AqIL9V4N

    And a substr_words() : http://codepad.org/jCLTm1zJ

  6. User Avatar
    Eddy Erkelens
    Permalink to comment#

    And a sencents-counter: http://codepad.org/o9I3zdI9

    All together, you can count sentences of a long text.
    Then cut it in half (use ceil() or abs()).
    Slice it with substr_sentences() and there you go.

  7. User Avatar
    Deepak Mishra
    Permalink to comment#

    Hi,

    I want to cut the sentence to 200 character after that read more link.
    Can you help me out.

  8. User Avatar
    Matt

    I have noticed a bug in this function. When my string is returned, each sentence ends in “.!?”, as the foreach ($end_characters) loop always tests $real_sentence for the presence of an end character, and when it adds the end character, that string is not updated, only the stored string is. So each time it loops through end_characters, the string does not contain a character, so one is added.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag