基于两个变量的组合字符截断文本


Truncating Text based on combined characters of two variables

我正在使用自定义函数根据说明允许字符数的参数截断文本。这是我的代码:

function bm_best_excerpt($length, $ellipsis, $content) {
$text = $content;
$text = strip_tags($text);
$text = substr($text, 0, $length);
$text = substr($text, 0, strripos($text, " "));
$text = $text.$ellipsis;
return $text;
}

在任何页面上,我都可以通过抓取 Wordpress 自定义字段(其中包含文本字符串)并通过此函数运行它来截断文本,如下所示:

<?php $excerpt = get_field('long_description'); ?>
<p><?php echo bm_best_excerpt(70, ' ... ', $excerpt); ?></p>

这很好用,并显示$excerpt的前 70 个字符。我想修改这个函数,所以它首先计算标题中的字符数(在描述上方),然后在此描述中使用任何剩余字符。

为了说明这一点,假设我想总共允许 80 个字符。我的原始 HTML 如下:

这是一个相当长的标题

下面是一些 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

我希望标题和描述之间的字符总数为 80。标题有 35 个字符,剩下 45 个字符用于描述。

我将如何修改上述函数以允许计算额外的内容变量(作为参数),然后对$length进行减法?我希望函数看起来像这样:

function bm_best_excerpt($length, $ellipsis, $content1, $content2) {

其中$content1是标题,$content2是描述

尝试将字符串加在一起并作为一个整体进行处理:

function bm_best_excerpt($length, $ellipsis, $content, $content2='') {
    // default content2 to empty string, allowing use of old method to still be valid
    $text = $content.' '.$content2; // add the second content to the end of the first