physaux Posted June 7, 2010 Share Posted June 7, 2010 Ok so, I am trying to replace all instances of "%" with a random character. I first tried this: $realoutput = str_replace("%",randomchar(),$realoutput); randomchar() is a custom function I have. My problem is that it replaces the % with only 1 result of "random char()". So with 12%12%12% I get 12R12R12R or 12P12P12P instead of something like 12O12Y12N. Any suggestions how I can get the result that I want? I can't seem to figure it out! :confused: Link to comment https://forums.phpfreaks.com/topic/204058-how-can-i-get-str_replace-to-replace-all-instances-with-a-changing-replacement/ Share on other sites More sharing options...
5kyy8lu3 Posted June 7, 2010 Share Posted June 7, 2010 you could loop through each character if cpu usage isnt' a big deal <?php for ( $i = 0; $i < strlen($String), $i++ ) { $Byte = substr($String, $i, 1); //takes one character $NewString .= str_replace("%",randomchar(),$Byte); } Link to comment https://forums.phpfreaks.com/topic/204058-how-can-i-get-str_replace-to-replace-all-instances-with-a-changing-replacement/#findComment-1068813 Share on other sites More sharing options...
ignace Posted June 7, 2010 Share Posted June 7, 2010 Why str_replace() on 1 character? Just compare it and change it, like $Byte = substr($String, $i, 1); //takes one character $NewString .= '%' === $Byte ? randomchar() : $Byte; Or something like: $char = '%'; $string = '12%12%12'; $pos = -1; while (true) { $pos = strpos($string, $char, $pos + 1); if (false === $pos) break; $string[$pos] = randomchar(); } Link to comment https://forums.phpfreaks.com/topic/204058-how-can-i-get-str_replace-to-replace-all-instances-with-a-changing-replacement/#findComment-1068897 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.