3v4l.org

run code in 300+ PHP versions simultaneously
<?php function elapsed_time(array $start) { $now = explode(' ', microtime()); $deltasec = $now[1] - $start[1]; $deltamsec = (float)$now[0] - (float)$start[0]; return $deltasec + $deltamsec; } $str = 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!'; $replacements = [ 'this_key' => 'love', 'this_one' => 'more love' ]; $start = '_$'; $end = '$_'; $new_reps = array(); $starttime = explode(' ', microtime()); for ($i = 0; $i < 10000; $i++) { foreach ($replacements as $key => $value) { $new_reps["_\$$key\$_"] = $value; } $output = strtr($str, $new_reps); } echo "$output\n"; echo "strtr: " . elapsed_time($starttime) . "\n"; $replacements = [ 'this_key' => 'love', 'this_one' => 'more love' ]; $starttime = explode(' ', microtime()); for ($i = 0; $i < 10000; $i++) { $replaced = preg_replace_callback('/_\$([^$]+)\$_/', function($matches) use ($replacements) { return $replacements[$matches[1]]; }, $str); } echo "preg_replace: " . elapsed_time($starttime) . "\n"; echo "$replaced\n";

preferences:
51.63 ms | 407 KiB | 5 Q