0

This is what I have:

<?php
    echo "<ul class='frony-feat-img'>";
    while ($row = $readresult->fetch() ) {  ?>
        <?php
            printf ('<li class="blog-post">
                <h3><a href="/%1$s/%2$s">%3$s</a></h3>
                <img src="/media/%5$s" width="" height="" alt="" />
                %4$s
                <a class="read-post" href="/%1$s/%2$s">Read More</a>
            </li>',
                $blog_url,
                $row['identifier'],
                $row['title'],
                $row['short_content'],
                $row['featured_image']
            );
        }
    echo "</ul>";
?>

I want to trim the length of $row['short_content'] to a certain string length and add [...] at the end. How do I do that without taking the returned value out of the array?

Please let me know if my question makes any sense!? Thanks.

1 Answers1

2

Replace $row['title'] by:

strlen($row['title']) > 10 ? substr($row['title'], 0, 10) . '[...]' : $row['title'];

Note: here the certain string length is of course 10.

Example:

$row['title'] = 'abcdef';
echo strlen($row['title']) > 10 ? substr($row['title'], 0, 10) . '[...]' : $row['title'];

echo '<br/>';

$row['title'] = 'abcdefghijkl';
echo strlen($row['title']) > 10 ? substr($row['title'], 0, 10) . '[...]' : $row['title'];

Returns:

abcdef
abcdefghij[...]

Note:

You should create an helper to do this, such as:

function truncate($string, $length) {
  return strlen($string) > $length ? substr($string, 0, $length) . '[...]' : $string;
}

Then use it this way:

           (...)
            $blog_url,
            truncate($row['identifier'], 10),
            truncate($row['title'], 10),
            truncate($row['short_content'], 10),
            truncate($row['featured_image'], 10),
        );
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153