note 73604 added to function.str-word-count

From: Date: Sat, 03 Mar 2007 01:02:19 +0000
Subject: note 73604 added to function.str-word-count
Groups: php.notes 
Request: Send a blank email to php-notes+get-124035@lists.php.net to get a copy of this message
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to: function Truncate($input, $numWords) { if(str_word_count($input,0)>$numWords) { $WordKey = str_word_count($input,1); $PosKey = str_word_count($input,2); reset($PosKey); foreach($WordKey as $key => &$value) { $value=key($PosKey); next($PosKey); } return substr($input,0,$WordKey[$numWords]); } else {return $input;} } The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all. Cheers! Josh ---- Server IP: 69.147.83.197 Probable Submitter: 74.114.220.131 ---- Manual Page -- http://www.php.net/manual/en/function.str-word-count.php Edit -- https://master.php.net/note/edit/73604 Del: integrated -- https://master.php.net/note/delete/73604/integrated Del: useless -- https://master.php.net/note/delete/73604/useless Del: bad code -- https://master.php.net/note/delete/73604/bad+code Del: spam -- https://master.php.net/note/delete/73604/spam Del: non-english -- https://master.php.net/note/delete/73604/non-english Del: in docs -- https://master.php.net/note/delete/73604/in+docs Del: other reasons-- https://master.php.net/note/delete/73604 Reject -- https://master.php.net/note/reject/73604 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124035) next »