我在 php 变量 $text 中存储了文本。该文本可以是 100、1000 或 10000 个单词。按照目前的实现,我的页面是根据文本扩展的,但是如果文本太长,页面看起来会很难看。
我想获取文本的长度并将字符数限制为 500 个,如果文本超出此限制,我想提供一个链接,说明“阅读更多”。如果单击“阅读更多”链接,它将显示一个弹出窗口,其中包含 $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;
您可以进一步调整它,但它可以在生产中完成工作。
关于php - 限制php中的文本长度并提供 'Read more'链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49404400/