开发者

Spinner problem - PHP foreach

I have a problem costomizing a script i found.

The script looks as the following:

function spin($var){
$words = explode("开发者_C百科{",$var);
foreach ($words as $word)
{
    $words = explode("}",$word);
    foreach ($words as $word)
    {
        $words = explode("|",$word);
        $word = $words[array_rand($words, 1)];        
        echo $word." ";

    }

}
}

$text = "Digitalpoint.com is {the best forum|a great Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);

I'd like to customize the script to return the value of the result.

Example:

$spin = spin($text);
echo $spin;

I've tried to generate a result variable by

$output = $output + $word." ";
return $output;

and then

$spin = spin($text);
echo $spin;

But i've always got result "0"... Can anyone come up with a clever solution for this problem? I'm looking forward to any tips/hints, thanks in advance!


Try this. The spun function wasn't returning a value. Instead of using echo, we'll just append the results onto string $spun and return that.

function spin($var){
$spun = "";

$words = explode("{",$var);
foreach ($words as $word)
{
    $words = explode("}",$word);
    foreach ($words as $word)
    {
        $words = explode("|",$word);
        $word = $words[array_rand($words, 1)];        
        $spun .= $word." ";
    }
}

return $spun;
}


This bit says that $output is the sum of $output and $word:

$output = $output + $word." ";
return $output;

Because they are not numbers, 0 is returned.

Try using these statements:

$output .= $word . " ";
return $output;


The problem is not in the code you provided, it's in the return statement you specified later on.

$output .= $word." ";
return $output;


I changed the function so that you are not duplicating variable names

function spin($var){
  $words = explode("{",$var);
  foreach ($words as $word)
  {
    $words2 = explode("}",$word);
    foreach ($words2 as $word2)
    {
      $words3 = explode("|",$word2);
      $word3 = $words3[array_rand($words3, 1)];
      echo $word3." ";

    }
  }
}

and i seem to be getting random phrases from the text. is this what you want?


This can also be done with just a preg_replace_callback:

function spin($text)
{
    return preg_replace_callback('/\{(.+?)\}/',
                                 function($matches) {
                                    $values = explode('|', $matches[1]);
                                    return $values[array_rand($values)];
                                 },
                                 $text);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜