I'm trying to solve the problem of translating to pig latin using PHP. I'm stuck, because Y can be both a vowel or a consonant depending on context. If Y is on the beginning of the word, is considered a consonant, if it is on the middle is considered a vowel.
For example "yellow style" becomes "ellowyay ylestay". With the rules being: "Words that start with a vowel (A, E, I, O, U) simply have "WAY" appended to the end of the word. Words that start with a consonant have all consonant letters up to the first vowel moved to the end of the word (as opposed to just the first consonant letter), and "AY" is appended. ('Y' is counted as a vowel in this context)"
My code is as following:
class Config{
public static $vowels = 'aeiou';
public static $vowelTermination = "way";
public static $consonants = 'b-df-hj-np-tv-z';
}
class Piglatin
{
public function convert($input)
{
$return = "";
$wordArray = explode(" ", $input);
foreach($wordArray as $word){
$return .= $this->translate($word);
$return .= " ";
}
return rtrim($return);
}
public function translate($input)
{
$translation = "";
if(!empty($input)){
if(is_numeric($input)){
return $input;
}
if($this->startVowel($input)){
$input = $input . Config::$vowelTermination;
return $input;
}
if($this->startConsonant($input) && strlen($input)===1 ){
return $input.'ay';
}
if($this->startConsonant($input)){
$input = preg_replace('/^([b-df-hj-np-tv-xz]*)([aeiouy].*)$/', "$2$1ay", $input);
return $input;
}
}
return $translation;
}
public function startVowel($input)
{
$regex = '/^['.Config::$vowels.']/i';
if(preg_match($regex, $input)){
return true;
}
return false;
}
public function startConsonant($input)
{
$regex = '/^['.Config::$consonants.']/i';
if(preg_match($regex, $input)){
return true;
}
return false;
}
}
Which given the input "yellow style" produces "yelloway ylestay" which is close to the expected result, but not quite.
Any idea on how to solve this?
See Question&Answers more detail:os