Limiting characters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Limiting characters

Post by psurrena »

Question: Say I have a news article stored in my database and I want to just list the title and a brief exerpt from in on say an index page.
Can I create an additional variable based on $body (below) that says to just return the first 100 characters or the article?

Thanks

Code: Select all

$query   = "SELECT title, body FROM news WHERE id=".$_GET['id']; 
    $result  = mysql_query($query) or die('Error : ' . mysql_error());  
    $row     = mysql_fetch_array($result, MYSQL_ASSOC);  
     
    $title   = $row['title']; 
    $body   = $row['body']; 
    $content .= "<hr><a href=\"news.php\">< Back</a><hr>
    			<p><strong>$title</strong></p>
    			<p>$body</p><hr>
    			<p><a href=\"news.php\">< Back</a> - <a href=\"#top\">Top</a></p><hr>";
User avatar
ddragas
Forum Contributor
Posts: 445
Joined: Sun Apr 18, 2004 4:01 pm

Post by ddragas »

Code: Select all

echo nl2br(substr($body, 0, 100)) .  " ... " ;
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Reading the Useful Post thread helps ;)

Which brings you how to properly chop text. Atleast this way you won't chop text in the middle of words, could even modify it to not chop in the middle of sentences I guess too.
Post Reply