Jump to content

PHP newbie question...


ffxpwns

Recommended Posts

Hi, I'm REALLY new to PHP, so any help would be appreciated :).  I'm trying to make a script that truncates a post after a certain amount of words (Below).  And I suppose the article would have to have $description="blahblahblah";.  My question is; how would I go about making this script actually work?  Where would I put the code and the articles? Like I said, I have less than 2 days experience with PHP, so please don't judge :)

// 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 the code that says when to truncate:

// replace 'xxx' with the number desired 

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

Link to comment
Share on other sites

Would this work better for the second snippet of code?  But I would still need to know the overall formatting.  I want it so logged in users can see the full article. 

 

$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>";

Link to comment
Share on other sites

// I would probably change this line...
if(false !== ($breakpoint = strpos($string, $break, $limit)))
// to this...
if ($breakpoint = strpos($string, $break, $limit))

 

It's just a preference, I suppose, but it makes more sense to me; because, the first line made me think you were checking if it weren't true, but it's a double negative check, where the second line is an affirmative check to continue with the following block.

 

Give this a test, though, just to be sure.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.