note 98198 modified in function.sprintf by visualmind

From: Date: Tue, 01 Jun 2010 12:29:26 +0000
Subject: note 98198 modified in function.sprintf by visualmind
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169779@lists.php.net to get a copy of this message
<?php function preg_sprintf($format,$params){ $result = ''; $anchor=0; $pattern = '/{([0-9a-zA-Z_]+)}/'; $n = preg_match_all($pattern, $format,$matches, PREG_OFFSET_CAPTURE); for($i=0; $i<$n; $i++){ $result .= substr($format, $anchor, $matches[0][$i][1]-$anchor); if(isset($params[$matches[1][$i][0]])) $result .= $params[$matches[1][$i][0]]; $anchor = $matches[0][$i][1] + strlen($matches[0][$i][0]); } $result .= substr($format, $anchor, strlen($format)-$anchor); return $result; } echo preg_sprintf('f {key} = {value}, {fas}b {key} {efs}',array('fas'=>'FAS', 'key'=>'KEY', 'value'=>'VALUE')); //will echo: f KEY = VALUE, FASb KEY ?> --was-- function preg_sprintf($format,$params){ $result = ''; $anchor=0; $pattern = '/{([0-9a-zA-Z_]+)}/'; $n = preg_match_all($pattern, $format,$matches, PREG_OFFSET_CAPTURE); for($i=0; $i<$n; $i++){ $result .= substr($format, $anchor, $matches[0][$i][1]-$anchor); if(isset($params[$matches[1][$i][0]])) $result .= $params[$matches[1][$i][0]]; $anchor = $matches[0][$i][1] + strlen($matches[0][$i][0]); } $result .= substr($format, $anchor, strlen($format)-$anchor); return $result; } echo preg_sprintf('f {key} = {value}, {fas}b {key} {efs}',array('fas'=>'FAS', 'key'=>'KEY', 'value'=>'VALUE')); //will echo: f KEY = VALUE, FASb KEY http://php.net/manual/en/function.sprintf.php

« previous php.notes (#169779) next »