PHPverse 2025

Voting

: min(six, eight)?
(Example: nine)

The Note You're Voting On

Nimja
13 years ago
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;
?>

<< Back to user notes page

To Top