note 83958 deleted from function.str-replace by philip

From: Date: Wed, 07 Oct 2009 08:01:37 +0000
Subject: note 83958 deleted from function.str-replace by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161454@lists.php.net to get a copy of this message
Note Submitter: jaimthorn at yahoo dot com ---- On the 19th of June, 2008, max at bitsonnet dot com posted a function interpolate that used create_function. I'd never seen create_function before and I thought it was very educational. Thanks, Maxim! However, the interpolate function can be improved, speed-wise: <?php function interpolate2($template, $hash, $prefix = '#{', $postfix = '}') { $tmp = array(); foreach($hash as $k => $v) { $tmp[$prefix . $k . $postfix] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $template); } echo interpolate2('Hello, #{username}. Welcome to #{site}.', array('username' => 'World', 'site' => 'php.net')); ?> According to my own tests, this version is somewhere between 4 and 5 times faster. Note, btw, that I used a very similar function on the sprintf page.

« previous php.notes (#161454) next »