例如我有以下代码:
<h3>My very long title</h3>
<h3>Another long title</h3>
如果我想使用 PHP 或 jQuery 缩短这些标题,我该如何将它们修剪成最接近的单词并附加一个省略号?是否可以指定字符数?
<h3>My very long...</h3>
<h3>Another long...</h3>
编辑 - 我怎样才能为每个头条新闻做到这一点?我真的不知道如何将每个标题传递到一个字符串中......
谢谢
最佳答案
这很容易使用 PHP 函数。看这个例子:
function trim_text($input, $length) {
// If the text is already shorter than the max length, then just return unedited text.
if (strlen($input) <= $length) {
return $input;
}
// Find the last space (between words we're assuming) after the max length.
$last_space = strrpos(substr($input, 0, $length), ' ');
// Trim
$trimmed_text = substr($input, 0, $last_space);
// Add ellipsis.
$trimmed_text .= '...';
return $trimmed_text;
}
然后您可以使用如下函数传入文本:
trim_text('My super long title', 10);
(我还没有对此进行测试,但它应该可以完美运行。)
关于php - 将标题修剪为最接近的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446034/