Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Help with PHP shorten text function

Options
  • 14-11-2005 3:46am
    #1
    Closed Accounts Posts: 4,842 ✭✭✭


    Hey,
    I have a function I use in PHP to shorten a string of text.
    function ShortenText($text) {
    
            $chars = 50;
    
            $text = $text." ";
            $text = substr($text,0,$chars);
            $text = substr($text,0,strrpos($text,' '));
            $text = $text."[...]";
    
            return $text;
    
        }
    

    What I was wondering is is it possible to change the last line ($text = $text."[...]"; ) so that it incorporates maybe an if statement so that if it's shorter than the 50 characters it won't display the [...]?

    It'd be something along the lines of
    function ShortenText($text) {
    
            // Change to the number of characters you want to display
            $chars = 50;
    
            $text = $text." ";
            $text = substr($text,0,$chars);
            $text = substr($text,0,strrpos($text,' '));
      
            if($text = longer_than($chars))
                  $text = $text."[...]";
    
            return $text;
    
        }
    
    or something along those lines.

    Any help would be appreciated. I'm using it to shorten the title of a forum on a phpBB board for an RSS feed


Comments

  • Closed Accounts Posts: 583 ✭✭✭^CwAzY^


    if (strlen($text) >= 50)
         $text = $text."[...]";
    

    Hope this helps :v:


  • Closed Accounts Posts: 4,842 ✭✭✭steveland?


    Cheers mate, managed to edit that around a little to negate the need to use the function at all if the text is shorter than the limit :v:
    function ShortenText($text) {
    
            $chars = 50;
    
           if (strlen($text) >=  $chars)
           {
                $text = $text." ";
                $text = substr($text,0,$chars);
                $text = substr($text,0,strrpos($text,' '));
                $text = $text."...";
           }
            return $text;
    
        }
    
    Thanks again :)


  • Registered Users Posts: 6,508 ✭✭✭daymobrew


    Don't forget to add comments, for you and any future maintainer. I couldn't figure out why you added the space.
    $text = $text." ";
    


Advertisement