str_replace - how to handle special circumstances? [duplicate]
Possible Duplicate:
PHP str_replace with for loop from array
How 开发者_JAVA技巧to replace a string (#stringA#) with elements from an array?... let's say we've a text:
'My shoes are #stringA# but #stringA#'
(the same string - #stringA#)
with $array:
$array[0] = 'comfy';
$array[1] = 'smells horrible';
so it'll be equal to 'My shoes are ' . $array[0] . ' but ' . $array[1];
- My shoes are comfy but smells horrible?
Usually in cases like this, you'd use %s as the string replacement and then use vsprtinf()
to replace the occurances of %s with values from an array. However, in a simple case like yours, you can also just replace the search strings with %s and achieve the same effect. For example:
<?php
$string = 'My shoes are #stringA# but #stringA#';
$key = "#stringA#";
$array[0] = 'comfy';
$array[1] = 'smells horrible';
$string = str_replace(array('%', $key), array('%%', '%s'), $string);
$newstring = vsprintf($string, $array);
echo $newstring;
?>
(The replacement of % to %% is to avoid any problems with printf symbols in general case)
精彩评论