Reputation: 994
So i have a list of articles, and I have a page in which shows 4 articles at a time and then shortens the description of the article to 1000 characters and allows users to "read more", my problem is within each post there could be tags IE: <i>
or <b>
<img>
<center>
etc, how when truncating the text can I see if there are any open tags within the div or within the called upon text?
Here is how it looks for now
$sum = strip_tags($article, '<a><i><b><u><center><br><img><a><span><iframe>');
if (strlen($sum) > 1000) {
$sumCut = substr($sum, 0, 1000);
$sum = substr($sumCut, 0, strrpos($sumCut, ' ')).'... <div class="right"><a href="article-' .$record[nid]. '">Read More</a></div>';
}
echo $sum;
For example
If I have...
Quisque imperdiet imperdiet fringilla. Quisque sit amet nibh odio. Fusce sit amet massa vitae mi faucibus viverra.
The code fo that would be <i>Quisque imperdiet imperdiet fringilla. Quisque sit amet nibh odio. Fusce sit amet massa vitae mi faucibus viverra.</i>
but if I were to set my truncating number to say 10, it would leave that tag open and thus everything afterwords would be in italics
Upvotes: 1
Views: 132
Reputation: 994
so dynamic got me close, but using strpos()
was the key, I added this to my code if ((strpos($sum, '<i>')) && (!strpos($sum, '</i>'))) { echo "</i>"; }
and one similar for each tag that I allow, next thing to do is to figure out how to make sure that there are no images or iframes near the end of the post, I will edit this to explain how I did that, but for now here is my code...
$sum = strip_tags($article, '<a><i><b><u><center><br><img><a><span><iframe>');
if (strlen($sum) > 1000) {
$sumCut = substr($sum, 0, 1000);
$sum = substr($sumCut, 0, strrpos($sumCut, ' '));
$cut = 1;
}else{
$cut = 0; }
echo $sum;
if ((strpos($sum, '<i>')) && (!strpos($sum, '</i>'))) { echo "</i>"; }
if ($cut==1) { echo '... <div class="right"><a href="article-' .$record[nid]. '">Read More</a></div>'; }
EDIT:
Okay, I figured out a better solution than making sure there were no images at the end of the post, I simply made the divs overflow: hidden;
in which it would resize for the images
EDIT:
I also had an issue with breaking the middle of a <br>
tag, it was leaving me with <br
a temporary fix seems to be to add another <br>
after everything which in these cases leaves the bad code <br<br>
but atleast everything works and isnt visible, but if anybody has a more viable solution please let me know
I hope this helps
Upvotes: 2
Reputation: 642
Using strpos()
, search for open tags within the first X characters (where X is the truncating number.) Then if true, add to a string.
Basically, (pseudocode)
if(first10chars.contains[use strpos here] "<i>" and !.contains "</i>") {
$endstr .= "</i>";
}
and do the same for the others. A pretty bad way but it'll work
Upvotes: 1