str_replace vs. preg_replace

Today I faced the problem of removing all occurances of a fixed number of characters from a string. I was curious how str_replace performed against preg_replace in this case.

Here's an example code that tries to simulate running both functions on a text of 100 sentences, each having 5-10 words and each word consisting of 10-20 characters. The sentences are separated by newlines and words are separated by spaces. The code runs both methods a 100000 times removing newlines, carriage return and tab characters from the random generated text.
<?php
set_time_limit
(240);
$input '';
$ord_a ord('a');
$max ord('z') - $ord_a;
for (
$i 0$i 100$i++) {
 
$s_len rand(510);
  for (
$j 0$j $s_len$j++) {
   
$w_len rand(1020);
   
$word '';
    for (
$j 0$j $w_len$j++) {
     
$word .= chr($ord_a rand(0$max));
    }
   
$input .= $word ' ';
  }
 
$input .= $word "\n";
}

$count 100000;
$start time();
for (
$i 0$i $count$i++) {
 
$output str_replace(array("\n""\r""\t"), array(''''''), $input);
}
print(
'time1: ' . (time() - $start));
$start time();
for (
$i 0$i $count$i++) {
 
$output preg_replace('/[\n\r\t]/'''$input);
}
print(
'time2: ' . (time() - $start));
?>

The difference is quite significant: str_replace performed almost a magnitude faster than preg_replace!

Syndicate content