Reputation: 365
For doing insensitive case search in strings which function is faster preg_match() or stripos()?
<?php
$string = "This is test string";
$result = preg_match('/test/i', $string);
OR
$result = stripos($string, 'test') !== false;
?>
Upvotes: 2
Views: 569
Reputation: 6524
stripos
is slow, better than use strtolower
than strpos
<?php
function loop()
{
$str_50 = str_repeat('a', 50).str_repeat('b', 50);
$str_100 = str_repeat('a', 100).str_repeat('b', 100);
$str_500 = str_repeat('a', 250).str_repeat('b', 250);
$str_1k = str_repeat('a', 1024).str_repeat('b', 1024);
$str_10k = str_repeat('a', 10240).str_repeat('b', 1024);
$str_100k = str_repeat('a', 102400).str_repeat('b', 1024);
$needle = 'b';
header("Content-Type: text/plain");
echo str_replace(',', "\t", 'count,strpos,preg,stripos,preg i,strpos(tolower)').PHP_EOL;
foreach(array($str_50, $str_100, $str_500, $str_1k, $str_10k, $str_100k) as $str)
{
echo strlen($str);
$start = mt();
for($i = 0; $i < 25000; $i++) $j = strpos($str, $needle); // strpos
echo "\t".mt($start);
$regex = '!'.$needle.'!';
$start = mt();
for($i = 0; $i < 25000; $i++) $j = preg_match($regex, $str); // preg
echo "\t".mt($start);
$start = mt();
for($i = 0; $i < 25000; $i++) $j = stripos($str, $needle); // stripos
echo "\t".mt($start);
$regex = '!'.$needle.'!i';
$start = mt();
for($i = 0; $i < 25000; $i++) $j = preg_match($regex, $str); // preg i
echo "\t".mt($start);
$str = strtolower($str);
$start = mt();
for($i = 0; $i < 25000; $i++) $j = strpos($str, $needle); // strtolower strpos
echo "\t".mt($start);
echo PHP_EOL;
}
echo PHP_EOL;
}
function mt($start = null)
{
if($start === null)
return microtime(true);
return number_format(microtime(true)-$start, 4);
}
loop();
Result in seconds
count strpos preg stripos preg i strpos(tolower)
100 0.0243 0.0395 0.0878 0.0339 0.0094
200 0.0100 0.0334 0.1636 0.0354 0.0103
500 0.0114 0.0368 0.4211 0.0415 0.0115
2048 0.0174 0.0556 1.5797 0.0653 0.0171
11264 0.0896 0.2727 8.7098 0.3531 0.0890
103424 0.8218 2.4429 79.7007 3.2986 0.8190
Upvotes: 0
Reputation: 157864
Some advanced search technology, like indexed fulltext search with either mysql or sphinx, would be a real solution for the "intensive search" problem.
While all this negligible comparison of these already inefficient functions involving full scan of data won't help.
If you insists on using those - no performance being your concern. Thus - do not waste anyone's time with comparison.
Upvotes: 0
Reputation: 1161
strpos is faster because this function has predefine rule what this function have to do... where in preg_match function we have to pass logic from our side... so in this case first have to define rule and work based on this
so strops is faster....
Upvotes: 0
Reputation: 60413
If you dont need to actually match a complex expression, or capture something then just use stripos
or strpos
Upvotes: 1