note 73577 modified in function.str-word-count by danbrown

From: Date: Fri, 31 Aug 2012 16:26:48 +0000
Subject: note 73577 modified in function.str-word-count by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190370@lists.php.net to get a copy of this message
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

<?php
function WordTruncate($input, $numWords) {
if(str_word_count($input,0)>$numWords)
{
	$WordKey = str_word_count($input,1);
	$WordIndex = array_flip(str_word_count($input,2));
	return substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return $input;}
}
?>

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh. --was-- I was interested in a function which returned the first few words out of a larger string. In reality, I wanted a preview of the first hundred words of a blog entry which was well over that. I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc. So, this is what I came up with: function WordTruncate($input, $numWords) { if(str_word_count($input,0)>$numWords) { $WordKey = str_word_count($input,1); $WordIndex = array_flip(str_word_count($input,2)); return substr($input,0,$WordIndex[$WordKey[$numWords]]); } else {return $input;} } While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words. The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position. Josh. http://php.net/manual/en/function.str-word-count.php

« previous php.notes (#190370) next »