note 46236 added to function.substr-count

From: Date: Sun, 03 Oct 2004 23:42:53 +0000
Subject: note 46236 added to function.substr-count
Groups: php.notes 
Request: Send a blank email to php-notes+get-77869@lists.php.net to get a copy of this message
In response to Jesse at bend dot com's comment regarding case insensitivity, if your substr_count() function is in a loop, never implement this: <?php // for each needle for($i=0; $<$n_needles; $i++){ // duplicating strtolower() process time on each iteration! OUCH! substr_count(strtolower($haystack), strtolower($needle[$i])); } // for each needle ?> I recommend implementing this instead: <?php // initiate lowercase instances of search text and needles $haystack_lower = strtolower($haystack); for ($i=0; $<$n_needles; $i++){$needle[$i] = strtolower($needle[$i]);} // after exploding // for each needle for($i=0; $i<$n_needles; $i++){ substr_count($haystack_lower, $needle[$i]); // assign this to whatever... } // for each needle ?> An example of the aforementioned arises if you are implementing, for instance, a search function in a help manual, when you check each user-entered search word against the manual text (like at the top of this page), and count the number of occurrences of each search word to weigh your results so you can display the best results first. If the above code is within ANOTHER loop traversing each of many manual pages, then you'll definitely get hammered on the iterative strtolower() process time. Always try to keep strtolower() outside the outermost loop, and query using use "SELECT LOWER(manual_text) FROM..." instead. Maybe this comment belongs in the strtolower() documentation? ---- Manual Page -- http://www.php.net/manual/en/function.substr-count.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46236 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46236&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+46236&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#77869) next »