substr(); to chop an entry

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Tubby
Forum Commoner
Posts: 28
Joined: Thu Oct 17, 2002 5:55 pm

substr(); to chop an entry

Post 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.
mark-s
Forum Newbie
Posts: 4
Joined: Thu Feb 05, 2004 11:04 am
Location: Newcastle, UK

Post 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!
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

$entry = substr($row['entry'], 0, strpos($row['entry'], ' ', 2000)); should cut the text at the first space after the 2000th character.
User avatar
Tubby
Forum Commoner
Posts: 28
Joined: Thu Oct 17, 2002 5:55 pm

Post 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.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

In my example i used ' ' to cut at a space, maybe you could use '>' to cut at a > instead ?
Post Reply