1. If a word starts with a consonant, put the first letter of the word at the end of the word and add "ay."
ex: happy = appyh + ay = appyhay
Here's a PHP script that translates input text into Pig Latin:
<?php
function toPigLatin($input) {
// Split the input into words
$words = explode(' ', $input);
$translatedWords = [];
foreach ($words as $word) {
$word = strtolower($word); // Convert to lowercase for simplicity
if (preg_match('/^[aeiou]/i', $word)) {
// If word starts with a vowel, simply add "yay" to the end
$translatedWords[] = $word . 'yay';
} else {
// If word starts with a consonant, find the first vowel
preg_match('/^[^aeiou]+/', $word, $matches);
$consonantCluster = $matches[0]; // Get the consonant cluster
$restOfWord = substr($word, strlen($consonantCluster)); // Rest of the word
$translatedWords[] = $restOfWord . $consonantCluster . 'ay';
}
}
// Join the translated words back into a string
return implode(' ', $translatedWords);
}
// Example usage:
$input = "happy coding world";
echo "Original: $input\n";
echo "Pig Latin: " . toPigLatin($input) . "\n";
?>
- Word Splitting: The input string is split into individual words using
explode()
. - Checking the Starting Letter:
Words starting with vowels (
a, e, i, o, u
) simply get "yay" appended. Words starting with consonants are modified by moving the leading consonant (or cluster of consonants) to the end of the word and appending "ay". - Regular Expressions:
/^[aeiou]/i
: Matches words starting with a vowel.
/^[^aeiou]+/
: Matches the leading consonant(s) of a word. - Joining Translated Words: Finally, the translated words are joined back into a sentence using
implode()
.
For the input "happy coding world"
, the script outputs:
Original: happy coding world
Pig Latin: appyhay odingcay orldway