One more quick php question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Publisher Bucks
    Confirmed User
    • Oct 2018
    • 1330

    #1

    Tech One more quick php question

    Im using the following on a page to limit the amount of characters are displayed for a products description:

    <?php

    function custom_echo($x, $length)
    {
    if(strlen($x)<=$length)
    {
    echo $x;
    }
    else
    {
    $y=substr($x,0,$length) . '...';
    echo $y;
    }
    }
    ?>
    Followed by calling the shortened description like this:

    <?php custom_echo($row['style-info'], 100); ?>
    It works perfectly however, I'm wanting to add this onto the end after the period marks:

    ... More

    With a clickable link using a link setup this way:

    domain.com/page.php?id=$ID

    How would I go about editing the code I'm currently using to facilitate that?

    I have tried adding the HTML code next to the periods but, that didnt work for some reason

    Should I be using something different entirely?

    Any help, pointers or advice would be appreciated.

    Thanks
    Extreme Link List - v1.0
  • vdbucks
    Monger Cash
    • Jul 2010
    • 2773

    #2
    not sure why you have that broken down into 12 lines, nonetheless...

    Code:
    <?php
      $output = strlen($input) > 50 ? substr($input,0,50)."..." : $input;
      echo $output
    ?>
    That's all you really need.

    Function method:

    Code:
    <?php
      $x = "This is a test of the emergency broadcast system. This is only a test. If this were a real emergency, you'd be dead";
      $length = 50;
    
      function truncate_text($x, $length) {
        $output = strlen($x) > $length ? substr($x,0,$length)."..." : $x;
        return $output;
      }
    
      echo truncate_text($x, $length);
    ?>
    Adapt to your use case, obv.

    Granted, this is a really archaic way of handling it given the fact you should be truncating by whole words, not single characters. The above example illustrates why (returned string is for the function above is "This is a test of the emergency broadcast system. ..."

    Comment

    • Publisher Bucks
      Confirmed User
      • Oct 2018
      • 1330

      #3
      How do I change that to truncate by words instead of characters but still keep the character count as close to 100 as possible?
      Extreme Link List - v1.0

      Comment

      • vdbucks
        Monger Cash
        • Jul 2010
        • 2773

        #4
        Code:
        <?php
        $input = "This is a test of the emergency broadcast system. This is only a test. If this were a real emergency, you'd likely be dead";
        $length = 100;
        
        $output = strlen($input) > $length ? substr($input, 0, strpos(wordwrap($input, $length), "\n"))."..." : $input;
        
        echo $output;

        Comment

        Working...