note 98198 deleted from function.sprintf by danbrown

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: Goose 

----

<?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
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.