down101102 2012-03-06 04: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-06 04: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-.

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

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序