1

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

4

2 回答 2

2

如此动态让我很接近,但使用strpos()是关键,我将它添加到我的代码中if ((strpos($sum, '<i>')) && (!strpos($sum, '</i>'))) { echo "</i>"; },并为我允许的每个标签添加一个类似的,接下来要做的是弄清楚如何确保在结尾附近没有图像或 iframe在这篇文章中,我将对其进行编辑以解释我是如何做到的,但现在这是我的代码......

$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>'; }

编辑:

好的,我想出了一个比确保帖子末尾没有图像更好的解决方案,我只是制作了overflow: hidden;可以调整图像大小的 div

编辑:

我也遇到了打破标签中间的问题<br>,它给我留下了<br一个临时修复似乎是<br>在所有这些情况下留下错误代码的所有内容之后添加另一个,<br<br>但至少一切正常并且不可见,但如果有人有更可行的解决方案请告诉我

我希望这有帮助

于 2012-06-08T19:53:43.640 回答
1

使用strpos(),在前 X 个字符中搜索打开的标签(其中 X 是截断的数字。)然后如果为真,则添加到字符串中。

基本上,(伪代码)

if(first10chars.contains[use strpos here] "<i>" and !.contains "</i>") {
$endstr .= "</i>";
}

并为其他人做同样的事情。一个非常糟糕的方法,但它会工作

于 2012-06-08T19:25:06.407 回答