在php中限制文本长度并提供"阅读更多"链接

Sco*_*ing 43 php text

我有文件存储在php变量$ text中.此文本可以是100或1000或10000个单词.正如目前实现的那样,我的页面基于文本扩展,但如果文本太长,页面看起来很难看.

我想获取文本的长度并将字符数限制为500,如果文本超出此限制,我想提供一个链接,说"阅读更多".如果单击"阅读更多"链接,它将显示包含$ text中所有文本的弹出窗口.

web*_*ave 137

这是我使用的:

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;
Run Code Online (Sandbox Code Playgroud)

您可以进一步调整它,但它可以在生产中完成工作.


Bri*_*n H 10

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);
Run Code Online (Sandbox Code Playgroud)


nek*_*ala 6

有一个合适的 PHP 函数: substr_replace($text, $replacement, $start).

对于您的情况,因为您已经知道文本长度的所有可能性(100、1000 或 10000 字),您可以简单地使用该 PHP 函数,如下所示:

echo substr_replace($your_text, "...", 20);
Run Code Online (Sandbox Code Playgroud)

PHP 将自动返回一个仅包含 20 个字符的文本...

单击此处查看文档


小智 5

我结合了两个不同的答案:

  1. 限制字符数
  2. 完整的 HTML 缺失标签

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $doc->loadHTML($stringCut);
        $yourText = $doc->saveHTML();
    }
    $yourText."...<a href=''>View More</a>"
    
    Run Code Online (Sandbox Code Playgroud)