How can I specify the length of the string more precisely?

Discussion in 'PHP' started by qwikad.com, Oct 24, 2013.

  1. #1
    I am using this to shorten long titles:

    
    
    <?php
    
    $title = $row['adtitle'];
    if (strlen($title) > 50) {
        $title = substr($title, 0, 50).'...';
    }
    echo $title;
    
    ?>
    
    
    Code (markup):
    The thing is it shortens them this way:

    Selling housing in OH. Stop by to check it ou...

    Make money working from home. Best opport...


    I want it to shorten them right before the last word, so that it would look like this:

    Selling housing in OH. Stop by to check it...

    Make money working from home. Best...


    Any ideas how to do that?

    Thanks!
     
    Solved! View solution.
    qwikad.com, Oct 24, 2013 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
  3. #3
    Try this:
    
    $title = $row['adtitle'];
    if (strlen($title) > 50) {
        $title = preg_replace('~\s+\S+$~', '', $title);
        $title = $title."...";
    }
    echo $title;
    
    PHP:
     
    Last edited: Oct 24, 2013
    jscg, Oct 24, 2013 IP
    qwikad.com likes this.
  4. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,373
    Likes Received:
    1,720
    Best Answers:
    31
    Trophy Points:
    475
    #4
    Working great. Thank you so much!
     
    qwikad.com, Oct 24, 2013 IP
  5. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,373
    Likes Received:
    1,720
    Best Answers:
    31
    Trophy Points:
    475
    #5
    Somebody on another forum pointed out that one line was missing (which probably you just forgot to add):

    <?php
    
    $title = $row['adtitle'];
    if (strlen($title) > 50) {
        $title = substr($title, 0,50);
        $title = preg_replace('~\s+\S+$~', '', $title);
        $title = $title."...";
    }
    echo $title;
    
    ?>
    Code (markup):
    Nonetheless, your code is working well too.
     
    qwikad.com, Oct 24, 2013 IP
  6. jscg

    jscg Well-Known Member

    Messages:
    161
    Likes Received:
    5
    Best Answers:
    3
    Trophy Points:
    108
    Digital Goods:
    2
    #6
    Yeah i have missed substr but im glad i have helped you with this :)
     
    jscg, Oct 24, 2013 IP