Forums

PHP

This topic is locked

trim dynamic text without chopping words

Posted 23 Apr 2006 07:24:39
1
has voted
23 Apr 2006 07:24:39 Andrew Ross posted:
I have a recordset that displays an article summary from my database like this:

<pre id=code><font face=courier size=2 id=code>&lt;?php echo $row_featured['summary']; ?&gt;</font id=code></pre id=code>

I figured out how to trim the output to a number of characters like this, but it cuts off words.

<pre id=code><font face=courier size=2 id=code>&lt;?php echo substr($row_featured['summary'],0,50); ?&gt; </font id=code></pre id=code>

Is there anyway to do this so it only displays whole words?

Thanks,

Andrew

Replies

Replied 24 Apr 2006 15:24:10
24 Apr 2006 15:24:10 Roddy Dairion replied:
There might be an easier way but this is will do the trick wiv some minor changes.
<pre id=code><font face=courier size=2 id=code>
&lt;?php
//Set where how many characters of the string you want to display
$chop_here = "10";

//You Text
$str = $row_featured['summary'];

//Split Text into, characters
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

$no_of_chars = count($chars);
if ($chop_here &gt; $no_of_chars)
{
$chop_here = $no_of_chars;
}
//for loop
$str = "";
for ($i = 0; $i &lt;= $chop_here; $i++)
{
//Saving each Characters in variable $text
$text = $chars[$i];
$str.=$text;
//check if for loop $i has reach end
if ($i == $chop_here)
{
//if true then checks if Characters to stop at is not the same as no of characters in text
if ($chop_here != $no_of_chars)
{
//if true then check that character in $text is not a blank space
if ($text != " "
{
//if character isn't then increment the value of where to stop cutting text
$chop_here++;
}
}
}

}
echo $str;
</font id=code></pre id=code>

Edited by - roders22 on 24 Apr 2006 15:25:17

Reply to this topic