-4

我想将字符串中的 2 个字符与其他 2 个字符交换。

开始字符串 = "`bHello `!how `Qare `%you."

随机字符串 = "1234567890abcdefghijklmnopqrstuvwxyz!£$%^&@"

我如何交换`b`!`Q `% 随机的所以看起来像这样

最终结果字符串 = "`4Hello `^how `$are `@you."

到目前为止我已经尝试过了

我试过到目前为止

$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);

然而最终的结果是

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

它只随机选择 1 个并将它们全部更改为那个。

4

1 回答 1

0
<?php
function randomChar() { 
    $rand = "1234567890abcdefghijklmnopqrstuvwxyz";
    return substr($rand, rand(0, strlen($rand)), 1);  
} 

echo preg_replace_callback("/`./", 'randomChar', "`bHello `!how `Qare `%you.");
于 2013-03-12T16:12:18.607 回答