将标题修剪到最接近的单词 [英] Trim headline to nearest word

查看:74
本文介绍了将标题修剪到最接近的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下代码:

<h3>My very long title</h3>
<h3>Another long title</h3>

如果我想使用PHP或jQuery缩短这些标题,如何将它们修剪到最接近的单词并附加省略号?可以指定字符数吗?

If I wanted to shorten these titles using PHP or jQuery, how can I trim them to the nearest word and append an ellipsis? Is it possible to specify a character count?

<h3>My very long...</h3>
<h3>Another long...</h3>

修改- 如何为每个头条新闻做到这一点?我真的不知道如何将每个标题转换为字符串...

Edit - How can I do this for each one of the headlines? I don't really have an idea as to how to pass each headline into a string...

谢谢

推荐答案

在PHP中创建省略号

<?php
function ellipsis($text, $max=100, $append='&hellip;')
{
    if (strlen($text) <= $max) return $text;
    $out = substr($text,0,$max);
    if (strpos($text,' ') === FALSE) return $out.$append;
    return preg_replace('/\w+$/','',$out).$append;
}
?>

然后可以通过以下方式使用此功能:

This function can then be used in the following way:

<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>

jquery Auto Ellipsis

这篇关于将标题修剪到最接近的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆