Preg_replace vs str_replace

I’ve been looking for benchmark tests that compare preg_replace with str_replace, but none was satisfying my exact situation.

My exact situation was, that once the page is completely loaded, all thousands of lines of html code, and then run that code through my function to replace the substring in it with mine. Actually converting all instances of http:// to https://.

Now there might be various solutions in your mind that we could do this and that, maybe yours is better too, but lets just see the comparison I found.

PHP 7 vs PHP 5.x (5.6, 5.5 tested)

I ran this test using PHP 7 originally. However I realized that in PHP 5.x version the results were totally different!

In PHP 7, preg_replace was faster for the following block of code used in my benchmark test. However in PHP 5.5 and PHP 5.6, the same code returned faster for str_replace!

Example to compare str_replace and preg_replace speeds

See this example code (with explanation as comments)

Test done online using: http://phptester.net/

<?php
//weirdly, I found preg_replace to be faster in this example code:
// (however, preg_replace wasn't able to handle a larger string, while str_replace handled much larger one (10+ times larger)

// storing the test start time
$start = microtime(true);

// adding a long string
$url = 'http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat http://nabtron.com/ some http://nabtron.com/ssldfkjlaksjd repeat 
<br>
';

$urlnew = '';

// making the string lengthier, to reflect a html output with thousands of lines of code
// change the value to 80000 and so on by adding more 0
for($i=0; $i <= 8000; $i++){
  $urlnew .= $i.$url;
}
//echo $urlnew;

$url = $urlnew;
 
// run them one by one to see the time consumed
$url = preg_replace('/http\:/', 'https:', $url);
//$url = str_replace('http:', 'https:', $url);

// time taken for execution 
$end = microtime(true); 
printf("<p>That took %f seconds.</p>\n", $end - $start);
?>

Running this code results in faster times for preg_replace than for str_replace in PHP 7 and opposite in PHP 5.6 and PHP 5.5. Here are my results.

Benchmark results

<using PHP 7.0>

preg_replace: 0.0252 seconds

str_replace: 0.0541 seconds

<using PHP 5.6>

preg_replace: 0.0346 seconds

str_replace: 0.0201 seconds

If you have any comments or corrections related to this benchmark between preg_replace and str_replace, please let me know!

2 comments on “Preg_replace vs str_replace

Leave a Reply

Your email address will not be published.