Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Help with PHP shorten text function

  • 14-11-2005 03: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, Registered Users 2 Posts: 6,680 ✭✭✭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