limit text length in php and provide #39;Read more#39; link(限制 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 中的文本长度并提供“阅读更多"链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:限制 php 中的文本长度并提供“阅读更多"链接
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
