Pregunta

I have the following code and need it to only echo out 100 words or less in the description rather than the entire description. Is there anyway to do that by editing this code?

public static function getExcerpt($profile) {
    $out='';
    if(!empty($profile['description'])) {
        $out.=$profile['description'].' '.__('', 'lovestory');
    }

    return $out;
}

Thanks!

¿Fue útil?

Solución

// for 100 characters...
if (strlen($profile['description']) > 100)
    $description = substr($profile['description'], 0, 100) . "...";
else
    $description = $profile['description'];

$out.= $description . ' ' . __('', 'lovestory');


// for 100 words
$out.= implode(" ", array_slice(explode(" ", $profile['description']), 0, 100)) .' '.__('', 'lovestory');

Otros consejos

You can simply use PHP's wordwrap function as shown below.

$text = "The quick brown fox jumped over the lazy dog.";
$newText = wordwrap(substr($text, 0, 20), 19, '...');
echo $newText;

will print The quick brown fox...

You can use explode with an empty space to create an array of words, and if there are more than 100 words, use array_slice to select the first 100, then implode that array back into a string

$words = explode(' ', $out);
if(count($words) > 100){
    return implode(' ', array_slice($words, 0, 100));
else{
    return $out;
}

That depends on how exact you want to be or how complicated your word boundaries are, but in general something like this would work for you:

$excerpt = explode(' ', $profile['description']);
$excerpt = array_slice($excerpt, 0, 100);
$out .= implode(' ', $excerpt).' '.__('', 'lovestory');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top