Session Ready
Exercise

Search and replace

The function str_replace() is a general function to replace parts of a string. A common application is to replace something with an empty string - which is a simple way to remove unneeded parts from a string.

With capturing groups, str_replace() gets even more interesting: They enable you to change the order of things. By adding so called "backreferences" to the replacement, str_replace() will replace these references with the contents of the corresponding capturing group. For example: If you write \\1, this will be replaced with the 1st capturing group.

In this exercise, you'll see the first use (remove a substring) and the second (reorder two parts of a string) side by side. In the scope, you'll find the variable top_10_lines from the last exercise.

Instructions
100 XP
  • Remove 3D from the end of each line in top_10_lines by replacing it with an empty string.
  • Form a new sentence with the two capturing groups. Reorder them so they result in e.g. "Karate Kid is on rank 1".