treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Truncate article when not logged in?

  • Hey, I have a (untested) truncation script. How would I make it so that the truncation script was enabled when the user was not logged in and when the user logged in they would see the full post. Thanks for the help!




    // this signifies how to truncate
    function myTruncate($string, $limit, $break=".", $pad="...")
    {
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit) return $string;

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
    $string = substr($string, 0, $breakpoint) . $pad;
    }
    }

    return $string;
    }

    And then for the length desired


    // replace 'xxx' with the number desired

    $shortdesc = myTruncate($description, XXX);
    echo "<p>$shortdesc</p>";

  • Would this work?
    <?php
    global $user;

    if (!$user->uid) {

    function myTruncate($string, $limit, $break=".", $pad="...")
    {
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit) return $string;

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
    $string = substr($string, 0, $breakpoint) . $pad;
    }
    }

    return $string;
    }

    }
    ?>
  • You don't want to wrap functions inside if statements otherwise things could get nasty.

    Just do something like this



    $description = 'This is the text I wish to either display in full or truncate';

    if ( !$user->uid )
    {
    $description = myTruncate($description, XXX);
    }

    echo "<p>$description</p>";