views:

234

answers:

3

I am grabbing info from three rows in my table, and echoing one of them in a anchor tag.

How can I limit the amount of characters on the $title variable that are shown in the anchor tag.

Code:

$results = mysql_query("SELECT * FROM news ");

while($row = mysql_fetch_array($results)) { 
    $id = $row['id'];
    $title = $row['title'];
    $date = $row['date'];

    echo "<a href=\"" . $_SERVER['PHP_SELF']."?id=$id"."\">$title</a> | ";
}

$thisID = $_GET['id'];

if(!isset($thisID)) {
    $thisID = 7;
}
+4  A: 

You can use substr:

echo "<a href=\"" . $_SERVER['PHP_SELF'] . "?id=$id" . "\">" . substr($title, 0, LENGTH) . "</a> | ";

Replace LENGTH with the length in characters to which you want to trim $title.

James McNellis
+1 beat me to it.
klabranche
A: 

You could replace the first part of the string, or the last part, but if you do it would be better to provide an indication that something has been left out, by appending or prepending an ellipsis ...

pavium
+2  A: 

You can use LEFT in the query to return the leftmost set of characters from a column.

It's in the format of LEFT(column, max_chars)

define('MAXCHARS', '50');

$results = mysql_query("SELECT id, LEFT(title, ".MAXCHARS.") as truncated_title, 
                           date FROM news");

Now when you go to retrieve the column, aliased by truncated_title in this example, it will only contain at most however many characters as set in your MAXCHARS constant.

random