I'm working on a script that allows students to input their answers into a form and gives them instant feedback on their answers.
I start with a string ($content) that contains the complete task with the gaps in square brackets, something like this:
There's [somebody] in the room. There isn't [anybody] in the room.
Is [anybody] in the room?
Now the script recognizes the solutions (somebody, anybody, anybody) and saves them in an array. The student's answers are also in an array.
To see if the answer is correct, the script checks if $input[$i] and $solution[$i] are identical.
Now here is the problem: I want the script to replace the placeholders with an input box where the solution is wrong and the solution in green where it's correct. This updated version of $content is then shown on the next page. But if there are two identical solutions, this results in multiple replacements as the replacement is replaced again...
I tried preg_replace with a limit of 1 but this doesn't do the trick either as it doesn't skip solutions that have already been replaced.
$i=0; while ($solution[$i]){ //answer correct if($solution[$i] == $input[$i]){ //replace placeholder > green solution $content = str_replace($solution[$i], $solution_green[$i], $content); } //answer wrong else{ //replace placeholder > input box to try again $content = str_replace($solution[$i], $solution_box[$i], $content); } $i++; } print $content; //Output new form based on student's answer
Is there any way to avoid replacing replacements?
I hope I didn't ramble too much... Have been wracking my brain for ages over this problem and would appreciate any suggestions.