dpjjr42626 2016-05-20 10:51
浏览 31
已采纳

PHP:字符串操作选择随机

I have the following string

Make me {cum|cumm}.... mmmm {Phones|Phone's} {gonna|going to|going}

There are some roles.

the text within curly brackets has one pipe Sign "|". means, either of two values.

If we take {Phone|Phone's} I want to choose one of them randomly and it can have more than two or three values or even a single value in curly brackets.

So the above string can result one of the following

  1. Make me cumm.... mmmm Phones going to

  2. Make me cumm.... mmmm Phone's going to

  3. Make me cum.... mmmm Phones going

  4. Make me cumm.... mmmm Phone's going to

Update

I had a longer solution

preg_match_all("~\{(.*?)\}~",$string,$matches);

    foreach($matches[1] as $match) {
        $options = explode("|", $match);
        if(count($options) > 0) {
            $key = array_rand($options);
            $randomValue = $options[$key];

            $string = str_replace("{".$match."}", $randomValue, $string);
        }
    }

    return $string;
  • 写回答

1条回答 默认 最新

  • dongzong5017 2016-05-20 10:59
    关注

    Use preg_replace_callback function, split matches, and take an random element of the resulting array

    $new = preg_replace_callback('/{([^}]+)}/', 
                                 function($i) { 
                                   $t = explode('|', $i[1]); 
                                   return $t[array_rand($t)]; }, 
                                 $string);
    echo $new;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计