drne47241 2013-03-12 16:04
浏览 40
已采纳

Php用2个其他随机字符替换2个字符

I want to swap 2 characters in a string with 2 other ones.

Start string = "`bHello `!how `Qare `%you."

Random string = "1234567890abcdefghijklmnopqrstuvwxyz!£$%^&@"

How do i swap `b `! `Q `% with random ones so it looks something like this

End result string = "`4Hello `^how `$are `@you."

I have tried this so far

I tried so far

$out = "`vHow `!are `@you."

$patterns = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`@","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");

$pretest = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`@","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");

$tempstr = $pretest[rand(0, strlen($pretest)-1)];

$substs = "`".$tempstr;

$out = preg_replace($patterns, $substs, $out);

However the end result is

$out = "`%How `%are `%you."

it picks only 1 random and changes them all to that one.

  • 写回答

1条回答 默认 最新

  • doutangliang7769 2013-03-12 16:12
    关注
    <?php
    function randomChar() { 
        $rand = "1234567890abcdefghijklmnopqrstuvwxyz";
        return substr($rand, rand(0, strlen($rand)), 1);  
    } 
    
    echo preg_replace_callback("/`./", 'randomChar', "`bHello `!how `Qare `%you.");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测