php - 将标题修剪为最接近的词

标签 php jquery wordpress-theming

例如我有以下代码:

<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/

相关文章:

php - 为什么 Normalizer::normalize (PHP) 不起作用?

php - 电子商务网站如何集成支付宝支付

javascript - Stripe 自定义结帐未发布

jquery - 在下拉菜单上被下推的内容

javascript - 使用 Colorbox 显示 div 时出现问题

php - 如何将 WordPress 类别选择限制为只有一个?

php - 简单的 php 解释.. 箭头运算符之间有什么区别?

Javascript 检查变量是否为 null 显示结果

css - WordPress更改特色图像的图像宽度和高度

Wordpress 单帖子类型模板不显示帖子