Showing only a certain amount of characters in PHP


24 of May2007

Say you want to post part of your blog on your front page, but only want to show the first 30 characters or so. This is way you do it:

 

<?php
$blog_content = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."; 

//how many characters should be shown?
$maxchars = "30";

$blog_content = substr($blog_content, 0, $maxchars);

//add a "..." at the end of the entry
$blog_content = $blog_content . "..."
?>

This takes the $blog_content variable and cuts it down to 30 characters, and then adds a … at the end of it.

Your Words


  1. Jamis, you genius! This is truly awesome. Thanks man!

Add Your Own


bluehost.com ad


Recent Posts

  • Lessons learned from Apple&#39;s Design Process
  • On why I started another Redesign when I had just finished one.
  • Why I chose Bluehost for cheap, reliable hosting (review)
  • Break; and continue; in javascript loops
  • Writing a prototype function in JavaScript
  • -->