Jump to content

display only part of a mysql table field


mattrd

Recommended Posts

Sorry, I really don't know what to call this in the title. but this is what I want to do. I built an online journal which all the info is stored in a mysql database. On the homepage of my site, I have a small box which is a "teaser" that will always show only the beginning of the latest journal post. Let's say... the first 200 characters or something along those lines. How do I get the box to only show the first 200 characters of the journal post? I'm very new to php & mysql so I really have no clue how to start doing this on my own. I thought about displaying everything and just using css to set the overflow to hidden, but this isn't ideal. Any help or any guidance in pointing me in the right direction would be extremely appreciated. Thank you.

Link to comment
Share on other sites

Here is a function to do what you want. Simply get the entire journal entry from the database and use this function to just display the teaser:

//Return a string up to a certain number of characters
//but will break on a space
function subStringWords($string, $length, $ellipse='...')
{
    if (strlen($string) <= $length) { return $string; }
    return array_shift(explode("\n", wordwrap($string, $length))) . $ellipse;
}

 

Just pass the function the string (obviously) and the max length of characters allows. Example:

echo subStringWords($journalText, 200);[code=php:0]

 

Optionally, you can specify the string to be appended at the end of the shortened text. By default the function will use ellipses. But, you could pass anything you want - even an empty string (or a link to the full text)

 

[code=php:0]$linkToFullEntry = " [<a href=\"viewEntry.php?id={$entryID}\">Read Entry</a>]";

echo subStringWords($journalText, 200, $linkToFullEntry);[code=php:0]

 

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.