Return to Snippet

Revision: 6291
at May 15, 2008 02:09 by skywalker


Initial Code
A function to limit text
Of course you can also copy this code and use it freely in the scripts that you may write.

php:


<?php
function limit_text( $text, $limit )
{
  // figure out the total length of the string
  if( strlen($text)>$limit )
  {
    # cut the text
    $text = substr( $text,0,$limit );
    # lose any incomplete word at the end
    $text = substr( $text,0,-(strlen(strrchr($text,' '))) );
  }
  // return the processed string
  return $text;
}
?>

How do I use this function?
Now to use it, you'll just have to paste the function above, into your script or onto a 'includes' file (containing all your functions) if you prefer.

Let's assume you want to paste it with your script - so, this is what you could do:

php:


<?php

//  Filename: test.php
//  ==================

//  Our sample text
$long = 'Offers a discussion board, news portal, '
       .'web-related articles, tutorials, scripts,'
       .' tech blog, photo gallery, oekaki drawing,'
       .' fun games, and more.';

//  we only want the text to be 15 characters long.
$short15 = limit_text( $long,15 );
//  perhaps we need one with just 6 characters.
$short06 = limit_text( $long,6 );

//  we output some text
echo "<p>$long</p>\n";
echo "<p>$short15</p>\n";
echo "<p>$short06</p>\n";

//  ============================================
//  now we paste our LIMIT_TEXT() function below
//  ============================================

function limit_text( $text, $limit )
{
  if( strlen($text)>$limit )
  {
    $text = substr( $text,0,$limit );
    $text = substr( $text,0,-(strlen(strrchr($text,' '))) );
  }
  return $text;
}
?>

Initial URL

                                

Initial Description
Another way of showing long text to end user...

Initial Title
Limited Text Function - PHP

Initial Tags
text, function

Initial Language
PHP