Page 1 of 1

substr(); to chop an entry

Posted: Fri Feb 13, 2004 4:46 am
by Tubby
Hello,
I've written myself a blog system, and on a page I want to display the first part of a blog entry.

Currently I'm using

Code: Select all

$entry = substr($row[entry], 0, 2000);
To chop the first 2000 characters from the entry and display them, however, some of the entries will contain links and images, and if they are around the 2000 characters mark the html might get chopped and screw everything up, example:
<img src="/im
<a href="http://ww

(The links are stored in the database using bbcode Image and moo.com is great which is then changed to html when it's grabbed from the database, if this makes any difference.)

Is there some way to get php to chop the entry to around about 2000 characters, if the 2000th character falls in the middle of an image or link then it will chop at the end of the image or link or the begining of it instead of part way through.

Hope you guys understand what I'm trying to do :)

Any help would be great.

Posted: Fri Feb 13, 2004 6:58 am
by mark-s
you could write a function that searches the entry string for all occurences of '<img' and searches it again for the matching number of closing tags. If the number of tags didn't match, you could chop the string before the last unclosed tag, or you could just add a closing tag on the end.

a bit rough, but it's something to start with!

Posted: Fri Feb 13, 2004 8:25 am
by markl999
$entry = substr($row['entry'], 0, strpos($row['entry'], ' ', 2000)); should cut the text at the first space after the 2000th character.

Posted: Fri Feb 13, 2004 8:37 am
by Tubby
markl999 wrote:$entry = substr($row['entry'], 0, strpos($row['entry'], ' ', 2000)); should cut the text at the first space after the 2000th character.
If the 2000th character is <im then it will cut it at <img, which still means it'll only have half of the actual code, but it makes it less likely to happen than how I was doing it, so thanks for the suggestion :)

Does anyone have any code suggestions to do what mark-s suggested?, It sounds like it could be what I'm after.

Posted: Fri Feb 13, 2004 9:09 am
by markl999
In my example i used ' ' to cut at a space, maybe you could use '>' to cut at a > instead ?