note 86068 added to function.sprintf

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
	$keys    = array_keys($array);
	$keysmap = array_flip($keys);
	$values  = array_values($array);
	
	while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
	{	
		if (!isset($keysmap[$m[1]]))
		{
			echo "No key $m[1]\n";
			return false;
		}
		
		$string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
	}
	
	array_unshift($values, $string);
	var_dump($values);
	return call_user_func_array('sprintf', $values);
}

echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
----
Server IP: 66.207.199.35
Probable Submitter: 208.124.157.118
----
Manual Page -- http://www.php.net/manual/en/function.sprintf.php
Edit        -- https://master.php.net/note/edit/86068
Del: integrated  -- https://master.php.net/note/delete/86068/integrated
Del: useless     -- https://master.php.net/note/delete/86068/useless
Del: bad code    -- https://master.php.net/note/delete/86068/bad+code
Del: spam        -- https://master.php.net/note/delete/86068/spam
Del: non-english -- https://master.php.net/note/delete/86068/non-english
Del: in docs     -- https://master.php.net/note/delete/86068/in+docs
Del: other reasons-- https://master.php.net/note/delete/86068
Reject      -- https://master.php.net/note/reject/86068
Search      -- https://master.php.net/manage/user-notes.php
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.