Hi folks,

I'm building a page that displays content from a database. I'm using CKEditor to add content to the database which includes basic html tags such as <p>, <img>, etc

On the page however, I want to shorten an article and have a more link below it.

An example of what I have:

//$content holds content data from my SQL

<?php
  $stripped_content = stripslashes($content);
  $final_content = preg_replace("/<img[^>]+\>/i", "", $stripped_content)
?>
<div>
  <?php echo substr($final_content, 0, 330) . ' ... </p>'; ?>
  <p style="text-align: right;">
    <a href="article.php?id=<?php echo $a_id; ?>">more</a>  &raquo;
  </p>
</div>

After various tests where I'm changing the length of the output, some results show broken html tags. Below example using Lorem Ipsum shows a broken closed </p> tag

Praesent non felis.< ...

Is there a way around this? Also, if anyone has tips on how I can manipulate my strings instead of using multiple variables and lines of code.

Thanks in advance

Recommended Answers

All 6 Replies

Run strip_tags on it first.

Run strip_tags on it first.

I considered this, however, I lose the formatting of the content provided by CKEditor.

I don't mind losing <img> tags, font formatting, but I'd really want to keep paragraphs intact.

Is it possible to mark where the <p> tags start and close, then strip the tags and rebuild it for outputting?

Actually, what I want is pretty similar to the mouseover's on the titles of each thread here on this forum, however, it strips the <p> tags as well.

$strip_tags($content, '<p><a>');

This strips all but <p> and <a> tags, however, I still get the same broken tag problem

Got something I'm looking at, but still a little buggy.

With a few mods, this article really helped me out with truncating strings with html tags

http://www.the-art-of-web.com/php/truncate/

$content = stripslashes($feedcontent_body);

// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break="</p>", $pad="...</p>")
{
  // return with no change if string is shorter than $limit
  if(strlen($string) <= $limit) return $string;
  // is $break present between $limit and the end of the string?
  if(false !== ($breakpoint = strpos($string, $break, $limit)))
  {
    if($breakpoint < strlen($string) - 1)
    {
      $string = substr($string, 0, $breakpoint) . $pad;
    }
  }
  return $string;
}

$shortdesc = myTruncate($content, 600);
echo $shortdesc;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.