Reputation: 6120
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;
}
Upvotes: 0
Views: 2526
Reputation: 9955
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.
Upvotes: 2
Reputation: 15128
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 ...
Upvotes: 0
Reputation: 355297
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.
Upvotes: 4