【问题标题】:PHP: Truncate text at word boundariesPHP:在单词边界处截断文本
【发布时间】:2009-08-13 07:56:00
【问题描述】:

有没有人知道 Drupal 用来转换以下字符串的函数的确切名称:

“你好,你好吗。还有一些文字。”

进入

“你好,怎么...”

即用于截断x个单词后的句子,然后添加省略号的功能。或者,如果有人有一个 php sn-p 可以做到这一点,那也很棒!

【问题讨论】:

标签: php drupal


【解决方案1】:
function getFirstWords($string, $words = 1)
{
    $string = explode(' ', $string);

    if (count($string) > $words)
    {
        return implode(' ', array_slice($string, 0, $words)) . '...';
    }

    return implode(' ', $string);
}

echo getFirstWords('Hello, how are you. Some more text.', 2); // Hello, how...

【讨论】:

  • getFirstWords('Hello, how are you. Some more text.', 10)。您可能想在添加省略号之前检查字符串是否已缩短。
【解决方案2】:

unicode.inc 中好像是truncate_utf8()。

【讨论】:

  • 这很奇怪,因为空格是 ASCII 字符,我看不出自定义 UTF-8 函数的原因。也许你可以把代码 sn-p 贴在这里?
  • api.drupal.org/api/function/truncate_utf8 不需要 drupal_substr() 和所有那些缓慢的废话。
  • @eyze:我没有使用 unicode 的经验,但我认为 UTF-8 函数的原因是为了保留多字节字符,其中后半部分可能是 0x20。
  • 确实如此,但是空格不会发生这种情况,就像 trim() 可以安全地用于 UTF-8 字符串一样。 phpwact.org/php/i18n/utf-8#utf-8_safe_functionality
【解决方案3】:

你可以使用函数views_trim_text($alter, $value)

查看更多详情https://api.drupal.org/api/views/views.module/function/views_trim_text/7

$alter['html'] = TRUE;
$alter['max_length'] = 200;
$alter['word_boundary'] = TRUE;
$alter['ellipsis'] = TRUE;
print views_trim_text($alter, $output);

【讨论】:

  • $alter 可以像在这个函数的第一个注释中的示例中那样在数组中分组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
相关资源
最近更新 更多