down101102 2012-03-05 20:45
浏览 58
已采纳

如何用随机集替换字符串中的一组字符?

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?

  • 写回答

1条回答 默认 最新

  • dongzha0813 2012-03-05 20:50
    关注
    $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-.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部