Questioner
Questioner

Reputation: 7463

How to replace a set of characters in a string with a random set?

Let's say I have a basic string of characters:

$string = "abcdeffedcbaabcdef";

What I want to do is search for a, c, and f, and then replace them with any one of these characters:

$replaceChars = array("1", "2", "3");

So as I search the string, each time I hit one of the characters I want to replace, I want to randomly pick from the pool of replacement characters, and then move onto the next character to replace and randomly select again, and so on...

I should end up with something like:

$string = "2b1de32ed1b21b2de3";

I can't quite make it come together, though. I think I want to use array_rand() maybe with some kind of foreach loop, using strpos() to go through and find each instance of the characters to replace.

What's slowing me down is that it seems that there seem to be many methods for stepping through an array so that one can apply a for or while loop, I can't see how to step through a string one character at a time.

How would I do this?

Upvotes: 2

Views: 890

Answers (1)

deceze
deceze

Reputation: 522626

$newStr = preg_replace_callback('/[acf]/', function () {
    static $replacements = array('1', '2', '3');
    return $replacements[array_rand($replacements)];
}, $str);

http://www.php.net/preg_replace_callback

This uses PHP 5.3+ anonymous functions for the callback, use more traditional methods for PHP 5.2-.

Upvotes: 4

Related Questions