preg_replace trim vs. trim

Regular expressions incur a significant amount of overhead. If there is a suitable PHP function, it should always be used before coding a regular expression.

<?php

$sWord = '   TestString    ';

/* Time preg_replace trim double quotes */
$fStartPreg=microtime(true);
$sPreg=preg_replace("/^\s+|\s+$/", "", $sWord);
$fEndPreg=microtime(true);

/* Time preg_replace trim single quotes */
$fStartPregSng=microtime(true);
$sPreg=preg_replace('/^\s+|\s+$/', '', $sWord);
$fEndPregSng=microtime(true);

/* Time trim */
$fStartTrim=microtime(true);
$sTrim=trim($sWord);
$fEndTrim=microtime(true);

/* Calculate elapsed times */
$fPregElapsed=$fEndPreg-$fStartPreg;
$fPregElapsedSng=$fEndPregSng-$fStartPregSng;
$fTrimElapsed=$fEndTrim-$fStartTrim;

/* Display output */
echo '<html>';
echo '<pre>';
echo htmlentities(file_get_contents('timetest.php'));
echo "\n\n";
echo '$sWord: -'.$sWord."-\n";
echo '$sPreg: -'.$sPreg."-\n";
echo '$sTrim: -'.$sTrim."-\n";
printf("preg_replace:\t%f<br />",$fPregElapsed);
printf("preg_replace:\t%f (single quotes)<br />",$fPregElapsedSng);
printf("trim:\t\t%f<br />",$fTrimElapsed);
printf("difference:\t%f<br />",$fPregElapsed-$fTrimElapsed);
echo '</pre>';
echo '</html>';

?>

$sWord: - TestString -
$sPreg: -TestString-
$sTrim: -TestString-
preg_replace: 0.000114
preg_replace: 0.000012 (single quotes)
trim: 0.000008
difference: 0.000106

This page also demonstrates the impact of single quotes vs. double quotes.