Page 1 of 1

Limiting output with substr?

Posted: Tue Feb 24, 2009 10:52 pm
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>

Re: Limiting output with substr?

Posted: Tue Feb 24, 2009 11:40 pm
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.

Re: Limiting output with substr?

Posted: Tue Feb 24, 2009 11:46 pm
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.