views:

1062

answers:

7

I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string?

So '12345678901234567890abcdefg' would turn into '12345678901234567890abcde...' where 'fg' is cut off.

A: 

substr function is the right one for you

usoban
+3  A: 

Really quickly,

$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
Peer Allan
can you tell me how to only add the ... if it is past 20 characters?
jiexi
See this answer: http://stackoverflow.com/questions/1241224/how-do-you-cut-off-text-after-a-certain-amount-of-characters-in-php/1241263#1241263
Chacha102
A: 
<?php echo substr('12345678901234567890abcdefg', 0, 20) . '...' ?>

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

Vincent Robert
A: 

You're looking for the substr method.

$s = substr($input, 0, 25);

This will get you the first chuck of the string and then you can append whatever you'd like to the end.

Hawker
A: 
 echo substr($str,0,25)."...";

Would do the trick, but if you are dealing with words, you might want to cut off on word boundries so you don't have partial word doig this: The quick bl...

So to do that (crude off the top of my head):

$words = split(" ", strlen($str));

for($i = 0,$j=0; $i< 25 && $j < sizeof($words) ;$j++)
{
    $i += strlen($words[$j]);
    echo $words[$j]. " ";    
}
echo "...";
Byron Whitlock
+3  A: 

May I make a modification to pallan's code?

$truncated = (strlen($string) > 20) ? substr($string', 0, 20) . '...' : $string;

This doesn't add the '...' if it is shorter.

Chacha102
Definitely much nicer like this
Peer Allan
A: 

To avoid cutting right in the middle of a word, you might want to try the wordwrap function ; something like this, I suppose, could do :

$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);

$lines = explode("\n", $wrapped);
var_dump($lines);

$new_str = $lines[0] . '...';
var_dump($new_str);

$wrapped will contain :

string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)

The $lines array will be like :

array
  0 => string 'this is a long string' (length=21)
  1 => string 'that should be cut in the' (length=25)
  2 => string 'middle of the first' (length=19)
  3 => string ''that'' (length=6)

And, finally, your $new_string :

string 'this is a long string' (length=21)


With a substr, like this :

var_dump(substr($str, 0, 25) . '...');

You'd have gotten :

string 'this is a long string tha...' (length=28)

Which doesn't look that nice :-(


Still, have fun !

Pascal MARTIN