tags:

views:

898

answers:

4

Does anybody have the exact name of the function Drupal uses to turn the following string:

"Hello, how are you. Some more text."

into

"Hello, how..."

I.e. The function that's used to cut off a sentence after x words, and then add an elipsis. Alternatively, if anybody has a php snippet that does this, that would be great too!

A: 

I think you're looking for truncation that respects word-boundaries. I don't know how Drupal does it, but there's decent code here.

Dominic Rodger
+3  A: 
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...
Alix Axel
`getFirstWords('Hello, how are you. Some more text.', 10)`. You probably want to do a check that the string has been shortened before adding the ellipsis.
Dominic Rodger
Fixed, thank you.
Alix Axel
A: 

It seems to be truncate_utf8() in unicode.inc.

too much php
That's weird, since space is a ASCII char I don't see the reason for a custom UTF-8 function. Maybe you could paste the code snippet here?
Alix Axel
http://api.drupal.org/api/function/truncate_utf8/ no need for drupal_substr() and all that slow crap.
Alix Axel
@eyze: I haven't had experience with unicode, but I presume the reason for a UTF-8 function is to preserve multi-byte characters where the second half might be 0x20.
too much php
Indeed, however that doesn't happen with spaces, the same way trim() can be used on UTF-8 strings safely. http://www.phpwact.org/php/i18n/utf-8#utf-8_safe_functionality
Alix Axel
A: 

http://api.lullabot.com/views_trim_text This is the function that is used..

Suchi