Jump to content

search string for half html tags


aleX_hill

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/207587-search-string-for-half-html-tags/
Share on other sites

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.

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...

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.