4

I am trying to limit the amount of text/data is being shown from MySQL not MySQL LIMIT but limiting it on the actual page like most blogs do. After certain text point they just display ...more, I know there is a function to do this in PHP but I am unable to remember its name could some one help me out with it?

PT Desu
  • 693
  • 4
  • 13
  • 26

7 Answers7

10
if(strlen($text)>1000){
    $text=substr($text,0,1000).' Read more';
}

you should understand that it can cut words and tags too.

RiaD
  • 46,822
  • 11
  • 79
  • 123
7
SELECT LEFT(content, 1000) FROM blog 

If you load entire content for example 30 000 chars and do substr(), you are wasting memory in order to show only 1000.

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • @John Magnolia, there many more MySQL native functions for strings, check out... http://dev.mysql.com/doc/refman/5.0/en/string-functions.html – Dejan Marjanović Aug 30 '11 at 20:31
3

You could use a function like this (taken from http://brenelz.com/blog/creating-an-ellipsis-in-php/):

function ellipsis($text, $max=100, $append='…')
{
    if (strlen($text) <= $max) return $text;
    $out = substr($text,0,$max);
    if (strpos($text,' ') === FALSE) return $out.$append;
    return preg_replace('/\w+$/','',$out).$append;
}

This won't cut a word in half like substr.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • Am open to suggestions for improvement :) – Alex Turpin Aug 01 '11 at 18:30
  • 1
    Well if you have 1000 word body, now you have a 1000 elements in an array... A quick google search came a crossed this: http://brenelz.com/blog/creating-an-ellipsis-in-php/ – iLLin Aug 01 '11 at 18:57
1

There are a few ways to do it, the easiest probably being substr()

$short = substr($long, 0, $max_len);
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
1

string substr ( string $string , int $start [, int $length ] )

It accepts two arguments. The first is the string that you would like to trim. The second is the length, in characters of what you'd like returned.

http://php.net/manual/en/function.substr.php

Matthew
  • 144
  • 1
1

Apply the wrap() function to get your shortened text, and replace "99" with the number of characters you want to limit it to.

function wrap($string) {
   $wstring = explode("\n", wordwrap($string, 99, "\n") );
   return $wstring[0];
}
sman591
  • 540
  • 6
  • 19
0
    <?

   $position=14; // Define how many character you want to display.

   $message="You are now joining over 2000 current"; 
   $post = substr($message, 0, $position); 

   echo $post;
   echo "..."; 

?>

This result shows 14 characters from your message

confucius
  • 13,127
  • 10
  • 47
  • 66