return only specified number of words
سؤال
I have some HTML tagged text, which I want to output only 40 words of.
e.g.
<strong>This is an article </strong> containing 150 words with <a href="">HTML
</a>tags and I want to output only first 40 words. How to do this?
I am using nl2br right now, because it has EOLs. explode()
and str_word_count
take into account only regular words.
المحلول
So after some googling I found what I was looking for (at this forum http://www.webmasterworld.com/forum88/10821.htm)
The function cuts specified number of characters from the string and then adds characters up to next space (to prevent cutting in the middle of a word).
function elliStr($string,$noChars) {
for ($i = 0; $i < strlen($string); $i++) {
$result = ($noChars+$i >= strlen($string) ? $string : ($string{$noChars+$i} == " " ? substr($string,0,$noChars+$i) : ""));
if ( $result != "" ) {
return nl2br($result);
}
}
}
لا تنتمي إلى StackOverflow