0

我无法弄清楚这段代码有什么问题。它只替换{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;
  }
}

这是怎么回事?

4

1 回答 1

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 );
    }
于 2012-11-25T10:55:00.337 回答