3

I want a program in php that takes the first letter of word to the last and add "ay" at end. example: I love my family becomes Iay ovelay ymay amilyfay

I did this to get my result:

<?php
$var = "I love my family";
$words = explode(" ",$var);
$final = "";
foreach ($words as $word){
    $n = "";
    for($i=1;$i<strlen($word);$i++){
        $n .= $word{$i};
    }
    $n .= $word{0}."ay";
    $final .= $n." ";
}
echo $final;
?>

but this doesnt work when the input is: he says, "I love my family". this gives output as: ehay ays,say I"ay ovelay ymay amily"fay where I need the punctuation marks to be in their own position like this: ehay ayssay, "Iay ovelay ymay amilyfay"

Tried alot but found nothing that works

6
  • Have you tried the to_pig_latin function?
    – Marty
    Jul 31, 2014 at 5:38
  • no, let me google and try that
    – LIGHT
    Jul 31, 2014 at 5:38
  • 3
    Heh I was kidding, writing up an answer now..
    – Marty
    Jul 31, 2014 at 5:39
  • Instead research regex. It's a one-liner without the explode and loop workaround.
    – mario
    Jul 31, 2014 at 5:40
  • 2
    @Marty Actually, if you google php pig latin you'll find some scripts that do it.
    – Barmar
    Jul 31, 2014 at 5:41

1 Answer 1

0

Looks like something along the lines of:

$str = 'he says, "I love my family"';
$str = preg_replace('/(\w{1})(\w*)/', "$2$1ay", $str);

echo $str; // ehay ayssay, "Iay ovelay ymay amilyfay"

Should get you at least most of the way there.

1
  • should be ehay ayssay, "Iay ovelay ymay amilyfay"
    – LIGHT
    Jul 31, 2014 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.