PHP Madlibs麻烦

时间:2012-11-25 10:48:03

标签: php class foreach

我无法弄清楚这段代码有什么问题。它只替换{info}短代码,将其他所有内容保留原样。

以下是代码:

class Compliment_Gen {

  public $madlib; 
  public $madlib_answers;
  public $madlib_line;
  public $new_compliment;

  //Sets up 'Madlibs' Arrays
  public function __construct()
  {
    $this->madlib = array("{great} {post}!", "{great} {post}! {thanks}!", 
                           "{great} {post}! {thanks} for this {info}!", 
                           "{great} {post}!, I've been looking for this {info}. {thanks}!", 
                           "{great} {info}.", "{great} {info}. {thanks}!", 
                           "I've been {looking for} this {info} for quite some time.", 
                           "{thanks} for this!", "{thanks} for this {great} {post}!"
                          );

    $this->madlib_answers = array('good job' => array ("good job", "nice work", "nicely done!", "excellent work!", "great job!"),
                         'post' => array ( "post", "article", "write up", "blog post", "piece"),
                         'great' => array ( "great", "amazing", "fantastic", "excellent", "solid" ),
                         'thanks' => array ( "thanks", "thank you", "thanks so much", "thank you so much"),
                         'looking for' => array ( "looking for", "looking everywhere for", 
                                                 "searching for", "searching everywhere for", "hoping for", "hoping to find"),
                         'info' => array ( "info", "information")
                         );

    $this->compliment_gen($this->madlib, $this->madlib_answers);
  }

  //One Random Compliment Produced
  public function compliment_gen($madlib, $madlib_answers)
  {
    $this->madlib_line = $this->madlib[rand(0, count($this->madlib)-1)];
    foreach( $madlib_answers as $seed => $spins)
    {
        $this->new_compliment = str_replace("{" . $seed . "}", $spins[ rand(0, count($spins)-1)], $this->madlib_line );
    }

    echo $this->new_compliment;
  }
}

发生了什么事?

1 个答案:

答案 0 :(得分:1)

请尝试以下操作,因为str_replace会为您提供替换字符串,因此每当您需要替换值来替换新值时。与您当前的代码一样,您将一次又一次地替换您的实际陈述

$this->madlib_line = $this->madlib[rand(0, count($this->madlib)-1)];
$this->new_compliment = $this->madlib_line;

foreach( $madlib_answers as $seed => $spins)
    {
        $this->new_compliment = str_replace("{" . $seed . "}", $spins[ rand(0, count($spins)-1)], $this->new_compliment );
    }