note 98198 modified in function.sprintf by visualmind
[email protected] Tue, 1 Jun 2010 05:29:26 -0700
Newsgroups
php.notes
Message-ID
<[email protected] >
<?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