note 36217 added to function.strpos

From: Date: Wed, 01 Oct 2003 13:20:39 +0000
Subject: note 36217 added to function.strpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-57537@lists.php.net to get a copy of this message
Function: stripos_words($haystack,'words in string') This function finds and reports positions of all words in supplied haystack. It returns the results as an array. The array has the following structure. Array ( [69] => Array ( [start] => 69 [end] => 74 [word] => honey ) [226] => Array ( [start] => 226 [end] => 232 [word] => cobweb ) } Where, for convenience, the main key also contains the positions of each found word occurrence. If you want the main key to be 0,1,2,3,etc then set the third parameter ($pos_as_key) to false; Hope this is of help to someone. Cheers, Justin :) // ================================== // CODE function stripos_words($haystack,$needles='',$pos_as_key=true) { $idx=0; // Used if pos_as_key is false // Convert full text to lower case to make this case insensitive $haystack = strtolower($haystack); // Split keywords and lowercase them foreach ( preg_split('/[^\w]/',strtolower($needles)) as $needle ) { // Get all occurences of this keyword $i=0; $pos_cur=0; $pos_found=0; while ( $pos_found !== false && $needles !== '') { // Get the strpos of this keyword (if thereis one) $pos_found = strpos(substr($haystack,$pos_cur),$needle); if ( $pos_found !== false ) { // Set up key for main array $index = $pos_as_key ? $pos_found+$pos_cur : $idx++; // Populate main array with this keywords positional data $positions[$index]['start'] = $pos_found+$pos_cur; $pos_cur += ($pos_found+strlen($needle)); $positions[$index]['end'] = $pos_cur; $positions[$index]['word'] = $needle; $i++; } } } // If we found anything then sort the array and return it if ( isset($positions) ) { ksort($positions); return $positions; } // If nothign was found then return false return false; } ---- Manual Page -- http://www.php.net/manual/en/function.strpos.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+36217 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+36217&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+36217&report=yes

« previous php.notes (#57537) next »