对于striing中每个单词的出现,用数组中的随机单词替换

时间:2017-01-30 04:12:31

标签: php regex

这是当前代码: -

 function randommacrofunc($string){

  $RandomTextArray =  array("Name","Think","Person","Apple","Orange","bananna"); 
  $count = substr_count($string, '{random}');
  $i = 0;
  //re:
  if ($i <= $count){
     shuffle($RandomTextArray);
     $string = str_replace('{random}', $RandomTextArray[$i], $string, $i);

     $i++;
     //goto re;
  }

  return $string;
}

我的目标是通过{random}数组中的单词提取替换字符串中每次出现的$RandomTextArray。加载时,它替换正确的单词,但所有相同的单词。例如:{random}{random}{random}返回AppleAppleApple位,我希望它返回ApplePersonThink

2 个答案:

答案 0 :(得分:2)

尝试使用raplace wit随机数组值:

<?php
 function randommacrofunc($string){

 $RandomTextArray =  array("Name","Think","Person","Apple","Orange","bananna");

 $count = substr_count($string, '{random}'); // count number of `{randome}` in the string

 for ($i = 0;$i<$count;$i++){ // iterate for loop till the count reach
       $string = preg_replace('/{random}/',  $RandomTextArray[rand(0,(count($RandomTextArray)-1))], $string, 1);
 }
 return $string; // return final replaced string
}

$string = '{random} string {random} string {random} string {random} string {random} string {random}';
echo randommacrofunc($string);

答案 1 :(得分:0)

虽然由于目标子字符串是静态({random})而使您的任务不需要正则表达式,但我还是更喜欢preg_replace_callback()的简洁语法。

预先翻转查找数组将简化替换过程。

代码:(Demo

$randoms = array_flip([
    "Name",
    "Think",
    "Person",
    "Apple",
    "Orange",
    "bananna"
]); 

$string = 'this {random} is {random} and {random} obviously.';

echo preg_replace_callback(
         '~\{random}~',
         function() use ($randoms) {
             return array_rand($randoms);
         },
         $string
     );

可能的输出:

this Name is Person and Orange obviously.