note 83958 added to function.str-replace

From: Date: Fri, 20 Jun 2008 11:52:10 +0000
Subject: note 83958 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-140618@lists.php.net to get a copy of this message
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. ---- Server IP: 213.249.64.162 Probable Submitter: 24.132.252.217 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/83958 Del: integrated -- https://master.php.net/note/delete/83958/integrated Del: useless -- https://master.php.net/note/delete/83958/useless Del: bad code -- https://master.php.net/note/delete/83958/bad+code Del: spam -- https://master.php.net/note/delete/83958/spam Del: non-english -- https://master.php.net/note/delete/83958/non-english Del: in docs -- https://master.php.net/note/delete/83958/in+docs Del: other reasons-- https://master.php.net/note/delete/83958 Reject -- https://master.php.net/note/reject/83958 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140618) next »