note 83945 deleted from function.str-replace by philip

From: Date: Wed, 07 Oct 2009 08:01:50 +0000
Subject: note 83945 deleted from function.str-replace by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161455@lists.php.net to get a copy of this message
Note Submitter: max at bitsonnet dot com ---- I always miss interpolate functionality in PHP, so I wrote this little helper method. It allows you to specify your own markup using $prefix and $postfix. <?php # Interpolate a string using hash. # by Maxim Chernyak ( http://mediumexposure.com ) function interpolate($template, $hash, $prefix = '#{', $postfix = '}' ) { $tokenize = create_function('$token', 'return "'. $prefix .'".$token."'.$postfix.'";'); $keys = array_keys($hash); $values = array_values($hash); $keys = array_map($tokenize, $keys); return str_replace($keys, $values, $template); } ?> For example: <?php $result = interpolate('Hello, #{username}. Welcome to #{site}.', array('username' => 'Hakunin', 'site' => 'php.net')); ?>

« previous php.notes (#161455) next »