0

I want to show snippets of 2 posts on the homepage. Here is the code I have:

    function getPostsHome() {
    $query = mysql_query("SELECT * FROM posts LIMIT 0,2") or die(mysql_error());
    while($post = mysql_fetch_assoc($query)) {
        echo "<h3>" . $post['Title'] . "</h3>";
        echo "<p>" . $post['Content'] . "</p><br /><br />";

    }
}

How do I truncate the Title to 25 characters, then '...', and the content to 100 characters, then '...'?

Thank you.

j0k
  • 22,600
  • 28
  • 79
  • 90
John Grier
  • 67
  • 1
  • 6

4 Answers4

0

try with this

function getPostsHome() {
    $query = mysql_query("SELECT * FROM posts LIMIT 0,2") or die(mysql_error());
    while($post = mysql_fetch_assoc($query)) {
      echo "<h3>" . (strlen($post['Title']) > 25 ? substr($post['Title'], 0, 25)."..." : $post['Title']) . "</h3>";
      echo "<p>" . (strlen($post['Content']) > 100 ? substr($post['Content'], 0, 100)."..." : $post['Content']) . "</p><br /><br />";
    }
}

sorry, now it's fixed

g3rv4
  • 19,750
  • 4
  • 36
  • 58
0

use substr() and strlen() functions:

Replace:

  echo "<h3>" . $post['Title'] . "</h3>";

With:

if(strlen($post['Title']) >25)
  echo "<h3>" . substr($post['Title'],0,25)."....</h3>";
else
   echo "<h3>" . $post['Title'] . "</h3>";
0

Hope this help :D

<?php
    function trunc($str, $len) {
        if (strlen($str) > $len) {
            $str = substr($str, 0, $len) . "...";
        }
        return $str;
    }


    $title = trunc($title, 25);
    $content = trunc($content, 100);

    echo $title;

?>
0

The other answers can produce strange results. Consider a string of 26 characters. In the other answers, this string is truncated to 25 chars + 3 "...". 28 chars for a string 26. That is not what you want. The good answer therefore is:

<?php
    function trunc($str, $len) {
        if (strlen($str) > $len+3) {
            $str = substr($str, 0, $len) . "...";
        }
        return $str;
    }


    $title = trunc($title, 25);
    $content = trunc($content, 100);

    echo $title;

?>
ASGM
  • 11,051
  • 1
  • 32
  • 53
Roemer
  • 1,124
  • 8
  • 23