note 107454 added to function.preg-match

From: Date: Fri, 10 Feb 2012 11:12:03 +0000
Subject: note 107454 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-186048@lists.php.net to get a copy of this message
When using a 'bad words reject string' filter, preg_match is MUCH faster than strpos / stripos. Because in the other cases, you would need to do a foreach for each word. With efficient programming, the foreach is ONLY faster when the first word in the ban-list is found. (for 12 words, 100,000 iterations, no word found) stripos - Taken 1.4876 seconds. strpos - Taken 1.4207 seconds. preg_match - Taken 0.189 seconds. Interesting fact: With long words ('averylongwordtospitepreg'), the difference is only much less. Only about a 2/3rd of the time instead of 1/6th <?php $words = array('word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10', 'word11', 'word12' ); $teststring = 'ThIs Is A tEsTsTrInG fOr TeStInG.'; $count = 100000; $find = 0; $start = microtime(TRUE); for ($i = 0; $i < $count; $i++) { foreach ($words as $word) { if (stripos($teststring, $word) !== FALSE) { $find++; break; } } } echo 'stripos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL; $start = microtime(TRUE); for ($i = 0; $i < $count; $i++) { foreach ($words as $word) { if (strpos($teststring, $word) !== FALSE) { $find++; break; } } } echo 'strpos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL; $start = microtime(TRUE); $pattern = '/'; $div = ''; foreach ($words as $word) { $pattern .= $div . preg_quote($word); $div = '|'; } $pattern .= '/i'; //Pattern could easily be done somewhere else if words are static. for ($i = 0; $i < $count; $i++) { if (preg_match($pattern, $teststring)) { $find++; } } $end = microtime(TRUE); echo 'preg_match - Taken ' . round($end - $start, 4) . ' seconds.' . PHP_EOL; ?> ---- Server IP: 213.249.64.162 Probable Submitter: 193.173.68.117 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- https://master.php.net/note/edit/107454 Del: integrated -- https://master.php.net/note/delete/107454/integrated Del: useless -- https://master.php.net/note/delete/107454/useless Del: bad code -- https://master.php.net/note/delete/107454/bad+code Del: spam -- https://master.php.net/note/delete/107454/spam Del: non-english -- https://master.php.net/note/delete/107454/non-english Del: in docs -- https://master.php.net/note/delete/107454/in+docs Del: other reasons-- https://master.php.net/note/delete/107454 Reject -- https://master.php.net/note/reject/107454 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186048) next »