如何在超出170字符后的第一个空格处添加省略号超链接?
实现长文本截断并添加带链接省略号的方案
看起来你需要处理一段可能过长的文本,当它的长度超过170字符时,在超出部分的第一个空格位置截断,再加上带超链接的省略号对吧?结合你给出的PHP变量场景,我整理了一个实用的实现方案:
基础实现(适用于单字节字符)
直接用PHP的字符串函数就能搞定,逻辑很清晰:
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many ..."; $maxAllowedLength = 170; $displayText = $postText; // 检查文本长度是否超限 if (strlen($postText) > $maxAllowedLength) { // 找到超出170字符后的第一个空格位置 $firstSpaceAfterLimit = strpos(substr($postText, $maxAllowedLength), ' ') + $maxAllowedLength; // 截断到该空格位置 $displayText = substr($postText, 0, $firstSpaceAfterLimit); // 添加带超链接的省略号(把括号里的地址换成你实际需要跳转的页面) $displayText .= " [...]"; } // 输出处理后的文本 echo $displayText;
多字节字符兼容版本(比如中文、特殊字符)
如果你的文本里包含多字节字符,用上面的单字节函数可能会截断到字符中间导致乱码,这时候换成多字节字符串函数就好:
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many ..."; $maxAllowedLength = 170; $displayText = $postText; if (mb_strlen($postText) > $maxAllowedLength) { $substringAfterLimit = mb_substr($postText, $maxAllowedLength); $firstSpaceAfterLimit = mb_strpos($substringAfterLimit, ' ') + $maxAllowedLength; $displayText = mb_substr($postText, 0, $firstSpaceAfterLimit); $displayText .= " [...]"; } echo $displayText;
关键逻辑说明
- 先判断文本长度是否超过设定的170字符阈值
- 找到超出阈值后的第一个空格,这样截断不会把单词拆成两半,保证可读性
- 拼接带超链接的省略号,用户点击就能跳转到完整内容页面
内容的提问来源于stack exchange,提问作者saikiran
相关产品推荐
相关产品推荐

