3v4l.org

run code in 300+ PHP versions simultaneously
<?php error_reporting(E_ALL); mb_internal_encoding('UTF-8'); $text1 = "Кажется, нас обнаружили! Надо срочно уходить отсюда, пока не поздно. Бежим же скорее!"; $text2 = "Ну, прости меня! Не хотела я тебе зла сделать; да в себе не вольна была. Что говорила, что делала, себя не помнила."; $text3 = "Идет гражданская война. Космические корабли повстанцев, наносящие удар с тайной базы, одержали первую победу, в схватке со зловещей Галактической Империей."; function makeFirstCharLowerCase(string $word): string { return mb_strtolower(mb_substr($word, 0, 1)) . mb_substr($word, 1); } function makeFirstCharUpperCase(string $word): string { return mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1); } /** * @return array<string> * @throws Exception */ function splitTextToSentences(string $text): array { $sentences = preg_split('/[.!?]/', $text, -1, PREG_SPLIT_NO_EMPTY); if (false === $sentences) { throw new Exception(preg_last_error_msg()); } return $sentences; } /** * @return array<string> * @throws Exception */ function splitSentenceToWords(string $sentence): array { $words = preg_split('/[-,;:\s]/', $sentence, -1, PREG_SPLIT_NO_EMPTY); if (false === $words) { throw new Exception(preg_last_error_msg()); } return $words; } /** * @param array<string> $words * @return array<string> */ function reverseWords(array $words): array { return array_reverse($words); } /** * @throws Exception */ function makeTextInYodaStyle(string $text): string { $sentences = splitTextToSentences($text); $result = ''; foreach ($sentences as $sentence) { $words = splitSentenceToWords($sentence); $reversedWords = reverseWords($words); $reversedWords[0] = makeFirstCharUpperCase($reversedWords[0]); $reversedWords[count($reversedWords) - 1] = makeFirstCharLowerCase($reversedWords[count($reversedWords) - 1]); $result .= implode(' ', $reversedWords) . '. '; } return $result; } $texts = [$text1, $text2, $text3]; $yodaText = ''; try { foreach ($texts as $text) { $yodaText = makeTextInYodaStyle($text); echo "Йода говорит: $yodaText\n"; } } catch (Exception $e) { echo "Произошла ошибка: " . $e->getMessage(); }

preferences:
54.93 ms | 413 KiB | 5 Q