3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Thesaurus { protected $synonyms = array( array('great', 'wonderful', 'amazing', 'fabulous', 'awesome', 'stunning'), array('look', 'see', 'observe') ); public function lookup($word) { foreach ($this->synonyms as $index => $synonym) { if (in_array(strtolower($word), $synonym)) { unset($synonym[ array_search($word, $synonym) ]); return $synonym[ array_rand($synonym) ]; } } return $word; } } class Transformer { protected $thesaurus; public function __construct(Thesaurus $thesaurus) { $this->thesaurus = $thesaurus; } public function transform($string) { foreach (str_word_count($string, 1) as $word) { $new_word = $this->thesaurus->lookup($word); if ($word !== $new_word) { if (ctype_upper($word[0])) { $new_word = ucfirst($new_word); } $string = $this->replace($word, $new_word, $string); } } return $string; } private function replace($needle, $replacement, $haystack) { echo $needle . ' ' . $replacement . PHP_EOL; return preg_replace( '/(?<!#)' . preg_quote($needle) . '(?!#)/', '#' . $replacement . '#', $haystack, 1 ); } } $transformer = new Transformer(new Thesaurus); foreach (range(1, 20) as $index) { echo str_replace('#', '', $transformer->transform('This is my great description. It really is wonderful. Look how wonderful it is.')), PHP_EOL; echo '-----------------------------------------------------' . PHP_EOL; }

preferences:
33.32 ms | 402 KiB | 5 Q