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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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