Re: str_replace
| From: | Nathan Rixham | Date: | Mon, 25 Apr 2011 23:27:42 +0000 |
| Subject: | Re: str_replace | ||
| References: | 1 2 | Groups: | php.general php.general |
| Request: | Send a blank email to php-general+get-312486@lists.php.net to get a copy of this message | ||
Jim Lucas wrote:
On 4/24/2011 8:44 AM, Ron Piggott wrote:just for fun $a = '%ECARBME%TIPLUP%%%%%%%E%%'; $b = 'abcdefghijklmnobqrstuvwxyz'; echo preg_replace('/%/e','substr(str_shuffle($b),-1)', $a );I am trying to figure out a syntax that will replace each instance of % with a different letter chosen randomly from the string $puzzle_filler. $puzzle_filler is populated with the letters of the alphabet, roughly in the same ratio as they are used. This syntax replaces each instance of % with the same letter: $puzzle[$i] = str_replace ( "%" , ( substr ( $puzzle_filler , rand(1,98) , 1 ) ) , $puzzle[$i] ); Turning this: %ECARBME%TIPLUP%%%%%%%E%% Into: uECARBMEuTIPLUPuuuuuuuEuu Is there a way to tweak my str_replace so it will only do 1 % at a time, so a different replacement letter is selected? This is the syntax specific to choosing a replacement letter at random: substr ( $puzzle_filler , rand(1,98) , 1 ); Thanks for your help. Ron The Verse of the Day “Encouragement from God’s Word” http://www.TheVerseOfTheDay.infoHow about something simple like this? <?php $input = '%ECARBME%TIPLUP%%%%%%%E%%'; $random_chars = range('a', 'z'); echo 'Before: '.$input.PHP_EOL; while ( ($pos = strpos($input, '%') ) !== false )$input[$pos] = $random_chars[array_rand($random_chars)];echo 'After: '.$input.PHP_EOL;