Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

displaying truncated(?) data in table? 2

Status
Not open for further replies.

xWastedMindx

Technical User
Joined
Sep 3, 2002
Messages
67
Location
US
Is there a way to display truncated text using PHP? (or any other method) -- similar to the way a text link or string gets cut off if it's too long and can't fit in the given table or display area -- (ie. bla bla bla ....) specifically bringing attention to the " ... "


Thanks in advance.
Kenny



 
yes use the substr() function

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

so to take the first 100 chars of a string

$part_str = substr ($myString, 0,100)



see the manual here

Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
The ... is called "ellipsis". You want to use a function to create an ellipsis only if the total is longer than the requested substring. If you really want to have it look professional you would only appen an ellipsis where there is a space in the string, not just in the middle of any word.

Here's some pseudo-op code, I'm confident you can code this yourself:
1. Compare length of string to maximum length
if shorter -> do nothing
2. if longer:
-) cut off the required number of chars (use substr()).
-) locate the last space in the snippet (strrpos())
-) cut the snippet to the correct length and append '...'

That's all. If you need more help just post a follow up.
 
I've tried using this 'substr' function in various places and methods, and can't get it to work correctly. I keep getting parse errors and stuff.

My guess is that I want to use the substr function in the section of my code which outputs my variables into the table... like so:

echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>substr(&quot;$dvdName&quot;)</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;;

But it doesn't seem to work.
The samples from the PHP manual all show the substr and string being tossed into another variable like so:
$rest = substr(&quot;abcdef&quot;, 1); // returns &quot;bcdef&quot;

But I don't understand what to do with that 'other' variable.
Help?

Here's my code to help me out if you'd like.. I'd be appreciated.

Code:
<?php

// Begin
	echo &quot;<table border='1' align='center' cellpadding='5' cellspacing='0' width='275'>
	<tr><td width='140'><b>DVD Name</b></td><td><b>DVD Price</b></td></tr>&quot;;

// Define colors for the alternating rows
$color1 = &quot;#E5E5E5&quot;;
$color2 = &quot;#DEE3E7&quot;;
$row_count = &quot;0&quot;;


 // Perform the Query
    $results = mysql_query(&quot;SELECT * FROM dvd&quot;) or die(mysql_error());

while ($row = mysql_fetch_array($results)) {

	$dvdName = $row[&quot;dvdName&quot;];
	$dvdPrice = $row[&quot;dvdPrice&quot;];


  // Some sort of equation that makes it work
$row_color = ($row_count % 2) ? $color1 : $color2;

// Table output here
echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>substr(&quot;$dvdName&quot;)</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;;

// Adds 1 to the row count
$row_count++;

}
// Close out your table.
echo &quot;</table>&quot;;
?>

 
Alright .. here's an update for you, and another question.

I got it to work... sort of.
I don't get any errors, but the php code about the substr is displaying in the data outputed to the page.

And now for the question.
If I'm suppose to give the 'start' and 'end' number values for the substr so it can truncate the string, and i'm outputting many strings.. what's a good number set to use? because their all different length strings, and i can't cut them all off at the space between words, and they might get cut in the middle of the word. how do i fix this?

 
to use substr you have to supply a start and end, in your posted code you did not include either of those.

once you have the variable, you can use substr to chop it in the php code, before you use the variable in the html code.

so instead of:

<td width='110' bgcolor='$row_color' nowrap>substr(&quot;$dvdName&quot;)</td>

it should be:

<?

if (strlen($dvdName) > 30) {
$dvdName= substr($dvdName, 0, 27) . &quot;...&quot;;
}

print(&quot;<td width='110' bgcolor='$row_color' nowrap>$dvdName</td>&quot;);

?>

it wouldnt look that bad to have a word chopped in the middle, i dont think. if try to only break it between words, you are going to complicate matters a lot, but you would need to use a function like strpos in conjuction with substr and a loop to figure out where the last word within the given limit is.


 
You have syntax errors in your code - be especially careful with the double quotes:
Code:
# wrong syntax
// Table output here
echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>substr(&quot;$dvdName&quot;)</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;;

# correct:
// Table output here
echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>&quot;;
echo(substr($dvdName,0,$maxlength));
echo(&quot;</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;);

Although variables are replaced inside double quotes, PHP code is not interpreted -> that's why the actual code appears, it is just handled as text.

Also, as miahmiah900 pointed out, you need the three parameters for substr(subject,start,length)
 
I see where I made my errors by comparing the code you wrote up for me.

It works great too! Thanks alot you guys! :-)

 
DRJ478:

Since it was your code that helped me more... I have another problem arising I hope you can help me with.

I have it working, although now I have just a 'presentation' error (if that's what you want to call it.)

For my data displayed now in the code up top more^^ -- even the text that doesn't get truncated still gets those &quot;...&quot; added to the end of it. I really don't need those on every single row of my displayed data.. just the ones that are too long to fit on the same line.

I assume I'd need to add an IF statement in there someplace, and probably some sort of other function to count the number of characters and it's its less than a certain amount, don't add the &quot;...&quot; to the end of it.

But I'm still fairly new and not sure how to go about doing this. I'll look around for the function in the PHP manual though. I think I've seen it before.



 
Got it.
I just need to elaborate a tiny bit on the code that miahmiah900 posted, because that one does exactly what you want. I'd structure it a bit differently, so here's how it goes:
Code:
// Table output here
echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>&quot;;
echo(showName($dvdName));
echo(&quot;</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;);

/**
 * showname 
 * Returns formatted string with ellipsis if length exceeds
 * defined maximum
 * parameters:
 * myText -> string
 * returns:
 * formattedText -> string
**/
function showName($myText){
   # set max characters
   $max = 30;
   # longer than max
   if (strlen($myText)>$max){
      return(substr($myText,0,$max-3).'...');
   }
return($myText);
}
The function returns the untouched text if it's shorter.
You need only call it like shown above and it will format the text.
I prefer this as it does not manipulate the original value of $dvdName.
 
in the bit of code i posted earlier, it has an if block that determines if the ... should be added on to the end or not:

<?

if (strlen($dvdName) > 30) {
$dvdName= substr($dvdName, 0, 27) . &quot;...&quot;;
}

print(&quot;<td width='110' bgcolor='$row_color' nowrap>$dvdName</td>&quot;);

?>

in the first line, you can change 30 to a different number to suit your needs (depending on what the maximum length you need is)

to cut it off at the nearest last word, you can do this instead: (though it may be buggy, i am just writing it off the top of my head)

<?

if (strlen($dvdName) > 30) {
$dvdName = substr($dvdName, 0, 30);
$strEnd = strripos($dvdName, &quot; &quot;);
$dvdName = substr($dvdName, 0, $strEnd) . &quot;...&quot;;
}

print(&quot;<td width='110' bgcolor='$row_color' nowrap>$dvdName</td>&quot;);

?>

hopefully, what is happening here is that if the variable $dvdName length is greater than 30, it is chopped to just 30 characters, then the last occurance of the space character is found and it is chopped again at that location and the ... is added to the end.
 
i'd like to comment that DRJ478's code is much more useful since it is a function :) the checking for the last word break code could easily be added as well.
 
DRJ478 -- I tried that code.. and I keep getting parse error on the line where it's declaring the $max = #



 
miahmiah900
Thanks. You posted the answer before the question was asked, so I can't take credit ;).
 
I just pasted the code and executed it without any parse errors - just as expected.
Let us see what your's looks like or compare it again.
 
Here's the entire chunk of code again.
The only thing I'm not sure of is --

1) Those $myText variables you have. Do you want me to change those or what?
I don't see those having any significance if they're using the 'myText' name.. so I'd assume I have to change them to $dvdName? so the info in the variable keeps passing correctly from one to the next .. etc.

2). Where exactly do I put that function, I've tried where you had it in the sample you gave me... and various other places (before the output, after the output).
I keep getting parse errors for the $max = # no matter where it goes.

Also.. if you can (or can't) tell... I do know what I'm talking about. And it seems I do have the logic for it, I just don't know exactly how to keep things structured and the syntax and all for it to work correctly.

Code:
<?php

// Begin
	echo &quot;<table border='1' align='center' cellpadding='5' cellspacing='0' width='275'>
	<tr><td width='140'><b>DVD Name</b></td><td><b>DVD Price</b></td></tr>&quot;;

// Define colors for the alternating rows
$color1 = &quot;#E5E5E5&quot;;
$color2 = &quot;#DEE3E7&quot;;
$row_count = &quot;0&quot;;


 // Perform the Query
    $results = mysql_query(&quot;SELECT * FROM dvd&quot;) or die(mysql_error());

while ($row = mysql_fetch_array($results)) {

	$dvdName = $row[&quot;dvdName&quot;];
	$dvdPrice = $row[&quot;dvdPrice&quot;];


  // Some sort of equation that makes it work
$row_color = ($row_count % 2) ? $color1 : $color2;

// Table output here

/**
 * showname
 * Returns formatted string with ellipsis if length exceeds
 * defined maximum
 * parameters:
 * myText -> string
 * returns:
 * formattedText -> string
**/
function showName($myText) {
   // set max characters
   $max = 22;
   // if longer than max
   if (strlen($myText)>$max) {
      return(substr($myText, 0, $max-3). &quot; ...&quot;);
      }
return($myText);
}

echo &quot;<tr>
<td width='110' bgcolor='$row_color' nowrap>&quot;;
echo(showName($dvdName));
echo (&quot;</td>
<td bgcolor='$row_color'>$dvdPrice</td></tr>&quot;);


// Adds 1 to the row count
$row_count++;

}
// Close out your table.
echo &quot;</table>&quot;;
?>

 
1. Yes, the $myText should be changed to $dvdName

2. page structure is fine. Function can be placed at the top or bottom of the page in even in-line as shown above. The only thing that matters is the that the function call goes in the right place where those changes are to take effect.

Can you show the parse error message?

Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
Bastien
Sorry, but I disagree that the variable name needs to be changed.
The variable $myText is local to the function showName() and of local scope. The name of that function internal variable does not matter at all. It is an intermediary receptacle for the the value that is initialized when the function is called in the page($dvdName). There is no need to rename it.
However, you can rename it to anything you want. $dvdName would not have anything to do with the larger scope var of the same name. The value is just passed to the receptacle, whatever you name it.

xWastedMindx
Bastien is right that it is better to keep the code cleanly organized.
Stick the function at the very end of the PHP code.

Again, there is no syntax error I could discern.
 
DRJ478

I agree that for the strict working purposes of the function, the var name does not need to be changed. i do it, and recommended it for consistency's sake. You know what var is being passed to the function and can trace it back thru the code later on.

regards

Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
I try and try ..and it still doesn't work.

Bastien:
Here's the error.

Parse error: parse error, unexpected T_VARIABLE in /var/ on line 123

Line 123 (or wherever I put the function call at), is the line where it's defining the '$max = #' variable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top