限制 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.
相关文章