note 110512 added to function.vsprintf

From: Date: Tue, 30 Oct 2012 23:47:02 +0000
Subject: note 110512 added to function.vsprintf
Groups: php.notes 
Request: Send a blank email to php-notes+get-191607@lists.php.net to get a copy of this message
Here is my example for named placeholders. It uses python like named placeholders except that it only allows /[a-z][a-zA-Z0-9_]/ for names. <?php /** * Returns a formatted string. Accepts named arguments. * @param string $format * @param array $args * @return string **/ function vsprintfn($format, $args) { // search format patterns preg_match_all('/((?:^|[^%])(?:%%)*)%(\([a-z][a-zA-Z0-9_]*\))?((\+|-)?(0| |\'.)?-?[0-9\.]*[bcdeEufFgGosxX])/', $format, $matches); // determine the order of the arguments $j = 0; $order = array(); foreach ($matches[0] as $i => $match) { if ($matches[2][$i] == '') { $key = $j++; } else { $key = substr($matches[2][$i],1,-1); } $order[] = $key; } // prepare the data array for vsprintf in the given order $data = array(); foreach ($order as $key) { if (isset($args[$key])) { $data[] = $args[$key]; } } // replace named format patterns with default format patterns $format = preg_replace('/((?:^|[^%])(?:%%)*)%(\([a-z][a-zA-Z0-9_]*\))((\+|-)?(0| |\'.)?-?[0-9\.]*[bcdeEufFgGosxX])/', '$1%$3', $format); // return formatted string return vsprintf($format, $data); } $exampleData = array(0=>2.2314123123,'test'=>2.1234883); echo vsprintfn('%%2.5f = %2.5f', $exampleData) . "\n"; echo vsprintfn('%%(test)09.5f = %(test)\'%9.5f', $exampleData) . "\n"; ?> ---- Server IP: 87.106.1.137 Probable Submitter: 178.27.7.106 ---- Manual Page -- http://www.php.net/manual/en/function.vsprintf.php Edit -- https://master.php.net/note/edit/110512 Del: integrated -- https://master.php.net/note/delete/110512/integrated Del: useless -- https://master.php.net/note/delete/110512/useless Del: bad code -- https://master.php.net/note/delete/110512/bad+code Del: spam -- https://master.php.net/note/delete/110512/spam Del: non-english -- https://master.php.net/note/delete/110512/non-english Del: in docs -- https://master.php.net/note/delete/110512/in+docs Del: other reasons-- https://master.php.net/note/delete/110512 Reject -- https://master.php.net/note/reject/110512 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#191607) next »