note 87932 added to function.sprintf
| From: | sven_pauli at gmx dot de | Date: | Wed, 31 Dec 2008 10:09:27 +0000 |
| Subject: | note 87932 added to function.sprintf | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-148712@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 217.160.72.57
Probable Submitter: 93.193.118.55
----
Manual Page -- http://www.php.net/manual/en/function.sprintf.php
Edit -- https://master.php.net/note/edit/87932
Del: integrated -- https://master.php.net/note/delete/87932/integrated
Del: useless -- https://master.php.net/note/delete/87932/useless
Del: bad code -- https://master.php.net/note/delete/87932/bad+code
Del: spam -- https://master.php.net/note/delete/87932/spam
Del: non-english -- https://master.php.net/note/delete/87932/non-english
Del: in docs -- https://master.php.net/note/delete/87932/in+docs
Del: other reasons-- https://master.php.net/note/delete/87932
Reject -- https://master.php.net/note/reject/87932
Search -- https://master.php.net/manage/user-notes.php