Limiting output with substr?

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
divito
Forum Commoner
Posts: 89
Joined: Sun Feb 22, 2009 7:29 am

Limiting output with substr?

Post by divito »

With the following code, I want to limit the $title to 25 characters, with "..." after any that go over, for each link that is returned. What is the best way to go about it?

Code: Select all

foreach ($rss->items as $item ) {
 
  if ($counter < 10) {
 
    $title = $item[title];
    $url   = $item[link];
    
    $counter++;
    $cs  = strpos($url, '/cs');
    $tf2 = strpos($url, '/tf2');
    $cod = strpos($url, '/cod');
    $wow = strpos($url, '/wow');
    $css = strpos($url, '/css');
    
  if ($cs == true) {
    ?>
  <tr>
    <td width="25"><div align="right"><?
    echo "<b>CS:</b><br>";?></td>
    <?
    ?><td width="605"><?
 
    echo "<a href=$url>$title</a></li><br>"; </td>
Drachlen
Forum Contributor
Posts: 153
Joined: Fri Apr 25, 2003 1:16 am

Re: Limiting output with substr?

Post by Drachlen »

Here's a really simple solution for you:

Code: Select all

$title = $item[title];
if( strlen($title) > 25 )
{
   $title = substr($title,0,25)."...";
}
 
All this does is check if the length of the string is greater than 25, and then uses the substr function to shorten it, then appends the "..."

And just for fun, a couple of shorthand ways of doing the same exact thing:

Code: Select all

$title = $item[title];
$title = (strlen($title)<25)?$title:substr($title,0,25)."...";
Or,

Code: Select all

$title = $item[title];
$title = substr($title,0,25).(strlen($title)>25?"...":"");
These achieve the same exact result.

Good luck.
divito
Forum Commoner
Posts: 89
Joined: Sun Feb 22, 2009 7:29 am

Re: Limiting output with substr?

Post by divito »

At first, I tried setting up substr with the echo of the link, but I couldn't work out how to make it work with the HTML. I figured I'd have to deal with the variable but didn't know how to go about it.

It works great, thanks a lot.
Post Reply