Your problem is that you are using two loops to process the data: You really want to use just one, and to heck with the replace function.
1) Loop through once, looking at each character in turn.
1.1) If it's "P", set "expecting Y" and start building a new string.
1.2) If it's "p", set "expecting y" and start building a new string.
1.3) If you are "expecting Y" then
1.3.1) If it's "Y" then print the string you built twice, and clear "expecting Y". 1.3.2) Otherwise, add it to the building string.
1.4) If you are "expecting y" then
1.4.1) If it's "y" then print the string you built three times, and clear "expecting y". 1.4.2) Otherwise, add it to the building string.
1.4) Otherwise, print the character once.
Try it on paper manually first, and you'll see what I mean!