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 中的文本长度并提供“阅读更多"链接


- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01