note 73577 added to function.str-word-count

From: Date: Thu, 01 Mar 2007 23:57:25 +0000
Subject: note 73577 added to function.str-word-count
Groups: php.notes 
Request: Send a blank email to php-notes+get-124002@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: 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. ---- 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/73577 Del: integrated -- https://master.php.net/note/delete/73577/integrated Del: useless -- https://master.php.net/note/delete/73577/useless Del: bad code -- https://master.php.net/note/delete/73577/bad+code Del: spam -- https://master.php.net/note/delete/73577/spam Del: non-english -- https://master.php.net/note/delete/73577/non-english Del: in docs -- https://master.php.net/note/delete/73577/in+docs Del: other reasons-- https://master.php.net/note/delete/73577 Reject -- https://master.php.net/note/reject/73577 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124002) next »