限制php中的文本长度并提供“阅读更多"链接 [英] limit text length in php and provide 'Read more' link

查看:80
本文介绍了限制php中的文本长度并提供“阅读更多"链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将文本存储在php变量$ text中.此文本可以是100或1000或10000个字.按照目前的实施方式,我的页面会根据文字进行扩展,但是如果文字太长,页面看起来就会很丑.

I have text stored in the php variable $text. This text can be 100 or 1000 or 10000 words. As currently implemented, my page extends based on the text, but if the text is too long the page looks ugly.

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

I want to get the length of the text and limit the number of characters to maybe 500, and if the text exceeds this limit I want to provide a link saying, "Read more." If the "Read More" link is clicked, it will show a pop with all the text in $text.

推荐答案

这是我使用的:

// 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;

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

You can tweak it further but it gets the job done in production.

这篇关于限制php中的文本长度并提供“阅读更多"链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆