个性化阅读
专注于IT技术分析

将标题修剪到最接近的单词

点击下载

例如, 我有以下代码:

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

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

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

编辑-如何为每个头条新闻执行此操作?我真的不知道如何将每个标题转换为字符串…

谢谢


#1


在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;
}
?>

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

<?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自动省略


#2


使用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(‘我的超长标题’, 10);

(我尚未对此进行测试, 但它应该可以正常工作。)


#3


也许你正在搜索wordwrap()。

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

使用$ break通过可选的break参数来换行。如果cutet设置为TRUE, 则始终将字符串包装在指定宽度或指定宽度之前。因此, 如果你输入的单词大于给定的宽度, 则会将其分解。

查阅php网站上的功能文档以获取更多示例。

+++

另一种解决方案是使用explode()将标题分隔为”(一个空格), 并提供最多5个单词的限制, 然后使用array_pop切断数组的最后一个元素, 最后使用”将它们与implode()连接起来(该空间)作为胶水。但是, 这种解决方案并不是最佳解决方案, 因为如果你说的话长, 它会给你带来难看的输出。


#4


如果你要在特定长度内, 则可以使用。

function truncateString($string, $length, $append = '...') {
    $length -= strlen($append); // length of "..."

    $string = substr($string, 0, $length);
    $string = substr($string, 0, strrpos($string, ' '));
    $string .= $append;

    return $string;
}
echo truncateString('My very long title', 15);

经过测试, 完美运行。

编辑:变成功能。


#5


看到这个问题:

function wrap($string, $limit) {
  $wstring = explode("\n", wordwrap($string, $limit, "\n") );
  return $wstring[0] . '...';
}

编辑:(包括<= $ limit检查)

<?php
function wrap($string, $limit) {
    if (strlen($string) <= $limit) {
        return $string;
    }
    $wstring = explode("\n", wordwrap($string, $limit, "\n"));
    return $wstring[0] . '...';
}
?>
<h3><?php echo wrap('My very long title', 12); ?></h3>

#6


使用一些PHP和强大的正则表达式

function formatHeadline($headline){
    if(preg_match('/(\w+\s+){3}/', $subject, $match)){
        return $match[1]  . '...';
    }
    return $headline;
}

使用regex和jquery在javascript中应该可以使用相同的方法。

jQuery也有省略号插件, 你可能需要调查一下。

赞(0)
未经允许不得转载:srcmini » 将标题修剪到最接近的单词

评论 抢沙发

评论前必须登录!