note 120286 deleted from function.explode by peehaa
| From: | peehaa@php.net | Date: | Sat, 10 Dec 2016 14:10:17 +0000 |
| Subject: | note 120286 deleted from function.explode by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208451@lists.php.net to get a copy of this message | ||
Note Submitter: daniel dot sentker at medialeitwerk dot de
----
A simple usage for the explode function to get an excerpt from a text.
<?php
/**
* @param int $maxWords
* @param string $ellipsis
*
* @return string
*/
function getExcerpt($text, $maxWords = 16, $ellipsis = '...')
{
$wordsCut = $maxWords-1;
$words = explode(' ', $text, $wordsCut);
if(count($words) < $wordsCut) {
return $text;
}
array_pop($words);
return implode(' ', $words) . $ellipsis;
}
$str = 'Hello World, i am fine!';
var_dump(getExcerpt($str, 4); // Outputs: Hello World, i am...
?>