View Full Version : cut down a variable?

02-10-2006, 12:54 AM
Is there a way to take a 482 charecter variable and cut it down to like 100 charecters and add a ... on the end?


02-10-2006, 12:56 AM
you could use substr, but if you have htmlentities you will need something like this(someone had passed this along to me):

substr($topic, 0, strrpos(substr($topic, 0, $chars_len), ' ')).'...';
but you only need to do that if the string is greater then your max value.

02-10-2006, 02:40 AM
I find it much easier to have complete words, so you might cut it like:

$str = 'Blue boy, blue boy. What do you say? Blue boy, blue boy.';

for($i = 0 $words = explode($str), $word_max = 6; $i <= $word_max; $i++) {
echo $words[$i];
if($i == $word_max) { echo '...'; }

02-10-2006, 07:29 AM
$str = $description;
for($p = 0 $words = explode($str), $word_max = 10; $p <= $word_max; $p++) {
echo $words[$p];
if($p == $word_max) { echo '...'; }

Parse error: parse error, unexpected T_VARIABLE, expecting ';' in C:\server\xampp\htdocs\css\maps.php on line 116
116 is the line with the for() on it. Also This is already in a for loop... would that create problems? I changed the i's to p's so that it wont get the two mixed together.

02-10-2006, 03:15 PM
Here is another method

function reverse_strrchr($haystack, $needle)
$pos = strrpos($haystack, $needle);
if($pos === false) {
return $haystack;
return substr($haystack, 0, $pos + 1);

function trimContent($content){
if(strlen($content) >150){
$content = substr($content,0,150);
$content = reverse_strrchr($content, ' ') . "...";
return $content;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
echo trimContent($str);