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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Help with PHP shorten text function

  • 14-11-2005 2: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,571 ✭✭✭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