問題描述
我將文本存儲(chǔ)在 php 變量 $text 中.該文本可以是 100 或 1000 或 10000 個(gè)字.按照目前的實(shí)現(xiàn),我的頁面基于文本進(jìn)行擴(kuò)展,但如果文本太長,頁面看起來很難看.
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.
我想獲取文本的長度并將字符數(shù)限制為 500,如果文本超過此限制,我想提供一個(gè)鏈接,說明閱讀更多".如果點(diǎn)擊閱讀更多"鏈接,它將顯示一個(gè)彈出窗口,其中包含 $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;
您可以進(jìn)一步調(diào)整它,但它可以在生產(chǎn)中完成工作.
You can tweak it further but it gets the job done in production.
這篇關(guān)于限制 php 中的文本長度并提供“閱讀更多"鏈接的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!