2009-08-13 50 views
3

有谁知道Drupal使用转以下字符串函数的确切名称:PHP:在单词边界截断文本

“你好,你怎么样一些文字。”

“你好,怎么......”

即用于在x个单词之后切断一个句子的函数,然后添加一个elipsis。另外,如果有人有这样做的PHP片段,那也会很棒!

+0

杜佩为http:// stackoverflow.com/questions/965235/how-can-i-truncate-a-string-in-php – 2009-08-13 08:06:45

回答

1

我认为你正在寻找截断尊重字边界。我不知道Drupal是如何做到的,但有代码here

6
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... 
+0

'getFirstWords('你好,你好吗,还有一些文字',10)'。您可能想要在添加省略号之前检查字符串是否已缩短。 – 2009-08-13 08:08:01

+0

修正了,谢谢。 – 2009-08-13 08:14:39

6

它似乎是truncate_utf8()unicode.inc

+0

这很奇怪,因为空间是ASCII字符我没有看到自定义UTF-8函数的原因。也许你可以在这里粘贴代码片段? – 2009-08-13 08:30:54

+2

http://api.drupal.org/api/function/truncate_utf8/不需要drupal_substr()和所有那些缓慢的废话。 – 2009-08-13 08:34:03

+0

@eyze:我还没有使用unicode的经验,但我认为UTF-8函数的原因是为了保留多字节字符,其中后半部分可能是0x20。 – 2009-08-13 08:54:31

1

可以使用功能views_trim_text($改变,$值)

查看更详细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); 
+0

$ alter可以像这个函数的第一条评论中的例子那样分组 – 2015-08-26 14:18:37