aleX_hill Posted July 13, 2010 Share Posted July 13, 2010 I have a string ($row['news']) extracted from my mysql database. Now if the string is too long, I want to trim it to 200 characters and put a "more" link at the end. The following does that fine: if(strlen($row['news']) > 200) { $row['news'] = substr($row['news'],0,200); $row['news'] .= " <a href=\"/news/id=$row[id]\">... read more</a>"; } The problem occurs when there is a HTML tag in the string (which is more then acceptable and required in this instance, mainly paragraph open and close tags). If the tag happens to be at the 200 character mark, I cut off half of the tag, which obviously causes display problems. So, is there a way that I can search the shortened string to see if I have trimmed a tag, and then remove that part of the tag. I would like to check for bold, italics, links and lists which are incomplete. Cheers Quote Link to comment Share on other sites More sharing options...
ChrisA Posted July 13, 2010 Share Posted July 13, 2010 A more robust solution would be to use PHP DOMDocument capabilities to edit the string so that you only count visible characters, and only remove plain text, not html tags. Unfortunately, its rather more complicated to set this up, but as I say, it will provide you with a robust method. Google search may provide a tutorial to follow. Quote Link to comment Share on other sites More sharing options...
aleX_hill Posted July 13, 2010 Author Share Posted July 13, 2010 Thanks for that. It is a little beyond my coding capabilities at the moment, but I will try and learn it when I get time. Hopefully in the mean time as a stop-gap measure someone can suggest something a little simpler. Quote Link to comment Share on other sites More sharing options...
ChrisA Posted July 13, 2010 Share Posted July 13, 2010 Fair enough. I would probably search the chopped string for the last '<', to see if it is after the last '>'. If it is, then you've probably half chopped a html tag. e.g. if(strlen($row['news']) > 200) { $news = substr($row['news'],0,200); $news .= " <a href=\"/news/id=$row[id]\">... read more</a>"; } // check if the last < is after the last > if (strrpos($news, '<') > strrpos($news, '>')) { // if so, chop off the bit from the last < onwards $news = substr($news, 0, strrpos($news, '<')); } Another option would be to strip html tags from the string before you chop it? Then you wouldn't have any issue with half chopped tags... Quote Link to comment Share on other sites More sharing options...
aleX_hill Posted July 13, 2010 Author Share Posted July 13, 2010 That looks like a good idea to me. Will give it a go tomorrow. The problem with removing tags is that I wont get the benefits of having them in there (ie links wont display). Thanks for the advice. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.