logo CodeStepByStep logo

replace_all

Language/Type: PHP recursion string return

Write a recursive function named replace_all that accepts three parameters: a string $s and two single-character strings $from and $to. Given these parameters, your function should return a new string that is the same as $s but with any occurrences of $from changed to $to.

For example, the call of replace_all("crazy raccoons", 'c', 'k') should return "krazy rakkoons" and the call of replace_all("BANANA", 'A', 'O') should return "BONONO".

Your function is case-sensitive; if the character $from is, for example, a lowercase 'f', your function should not replace uppercase 'F' characters. In other words, you should not need to write code to handle case issues in this problem.

Constraints:

  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) or strings to solve this problem.
  • (The point of this problem is to solve it recursively; do not use a library function to get around recursion.)
  • Do not call any string member functions or string library functions that traverse or search the entire string.
  • You can declare as many primitive variables (e.g. integers) as you like.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.