note 87932 deleted from function.sprintf by danbrown
| From: | danbrown@php.net | Date: | Wed, 31 Dec 2008 18:56:51 +0000 |
| Subject: | note 87932 deleted from function.sprintf by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-148726@lists.php.net to get a copy of this message | ||
Note Submitter: sven_pauli at gmx dot de
----
Be careful with the key-based printf stuff by jaimthorn at yahoo dot com and some others: The
routines using str_replace are perfectly broken!
Consider this:
<?php
$str = 'this AA is BB a CC test';
$find = array('AA', 'BB', 'CC');
$replace = array('BB', 'foobar', 'barfoo');
echo str_replace($find, $replace, $str);
?>
This will echo "this foobar is foobar a barfoo test", i.e. it first replaces AA by BB and
in the resulting string ("this BB is BB a CC test") it goes on with replacing BB by foobar
etc.
Please keep this in mind. Thus, this approach might be more useful to you (for single letter keys):
<?php
function keysrintf($str, $args) {
$result = '';
$start = 0;
while ( ($stop = strpos($str, '%', $start)) !== false ) {
/* Append leading part */
$result .= substr($str, $start, $stop - $start);
$stop++;
if (!isset($str{$stop})) {
/* Missing key */
return $result;
}
elseif ($str{$stop} != '%') {
if (!isset($args[$str{$stop}])) {
/* Unknown key */
$result .= '?';
}
else {
$result .= $args[$str{$stop}];
}
$stop++;
}
$start = $stop;
}
/* Append rest */
$result .= substr($str, $start);
return $result;
}
?>