If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Shorten a string?

Hey, there's a string I'm taking from a database and displaying. I would like to shorten that string if it is longer than a certain number of characters and add "..." at the end. How would I do this? Thanks.

that will be fine if this is the one and only time you will EVER need to do this, including not only in this script but forever, which the liklihood of you encountering something else you would like to limit is very very slim.

Twey was giving you a generic fuction that you could re-use over and over and over. and cover a number of parameters and options.

but we aren't here to dictate how you write your site, so I'm happy you found the solution. a good reference is www.php.net which is the homesite of the programming language, and it is very well documented.

Twey, I thought it was just a check to see whether or not to include the tail but what shook me was

$utail = count($tr) > $wordlimit;

$utail = $utail || strlen($tr) > $charlimit;

That first one is the one that threw me off because its setting the tail by default where the second is creating a check first?

The main problem with this is that it's liable to cut off the string halfway through a word: "I welcome you all here tod" while mine will try not to do so where possible: "I welcome you all here today..." That was the main problem I was trying to solve. The hard character limit is off by default but should probably be set too, since otherwise one very long word wouldn't get truncated.

That first one is the one that threw me off because its setting the tail by default where the second is creating a check first?

What? The former is equivalent to:

Code:

if(count($tr) > $wordlimit) // if there are more words than allowed
$utail = true;

And the latter:

Code:

if($utail || strlen($tr) > $charlimit)
$utail = true;

Without the check for $utail, the function wouldn't append the dots if the string were truncated by words and then was shorter than the character limit.

function cut_it($str,$len=20) { //default is 20, but you can switch to anything you want here on when calling itif (strlen($str)<=$len) { return $str; }$str = wordwrap($str,$len); //defaults to the behaviour twey setup$str = explode("\n",$str,2); //lazy-- you could use substr/strpos, etcreturn $str[0];}$test = 'whatever and stuff this is some text etc';$test = cut_it($test,15);