...

View Full Version : displaying first x characters, but not cutting in the middle of the word



DoubleV
04-22-2004, 07:25 PM
I want to display the forst x characters of a db text field, which I guess I can do using a substring. But I don't want it to cut off in the middle of the word. How would I accomplish that?

bcarl314
04-22-2004, 07:35 PM
Hmm, I know I've seen this here before.

How about something like...



$text = preg_match_all("/(.{1,50}\s.{1,15})?/",$dataBaseText,$matches);
print $matches[0];



Not tested, but something similar should work.

raf
04-22-2004, 07:41 PM
Yes. Has been posted here before. I use this



/*jesus at home dot com
03-Apr-2003 08:53
How to make a nice trim of text without break words in the middle :*/

$maxTextLenght=125;
$aspace=" ";
if(strlen($text) > $maxTextLenght ) {
$text = substr(trim($text),0,$maxTextLenght);
$text = substr($text,0,strlen($text)-strpos(strrev($text),$aspace));
$text = $text.'...';
}

So you cut of, the run a reverse search for a space and do a substr with that is number of characters.

Of course, when i pull it from a db, i do the initial chopping of with sql


sql="select left(variable, 125) as variable from table";
...
$aspace=" ";
if(strlen($text) > $maxTextLenght ) {
$text = substr($text,0,strlen($text)-strpos(strrev($text),$aspace));
$text = $text.'...';
}

DoubleV
04-22-2004, 11:03 PM
Yes. Has been posted here before.
I did a search, so I saw that. But i got confused, so figured I'd ask again.




sql="select left(variable, 125) as variable from table";
can you please explain what "variable" should stand for in this line?

raf
04-23-2004, 12:01 AM
inside the left-function, this needs bto be the name of the column /control /variable inside your table. The column you wan't to pulle the value from. The second variable is then an alias (could be the same name as the original columname. I suppose you'll kknow that 'table' needs to be replaced by the tablename.

misterx
04-23-2004, 04:11 AM
Don't forget about the awesome concatenation operator! Kind of a silly revision but you could modify the last line like this:

from:

$text = $text.'...';

to:

$text .= '...';

Makes no difference....I just like small code so I try to squeez out extra stuff wherever I can. :p



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum