如何字符串替换忽略另一个字符串中的字符串

How to STRING REPLACE that ignores the string inside of another string

这是我的问题的 TLDR 版本:
有什么方法可以在字符串 "q11-q2" 上执行 str_replace ,其中执行 str_replace("q1","45", "q11-q2") 不会替换 "q1" "q11" 的一部分?

更多详情
我正在开发一个财务计算器,用户可以在其中输入财务数据,然后我们输出结果。由于我不会深入的原因,我们不会将公式编写为代码,我们需要将公式作为字符串保存在 table 中。例如,table 的列如下所示:
*((q2/4)*0.25)49
q10/(q2/4)


我需要将问题 1 到 12 的答案插入到分别表示 q1、q2、...q10、q11、q12 的公式中。为此,我正在做:

$query= ///here i'd select each formula
while ($row=mysqli_fetch_array($query)):
     $formula=$row['formula']; ///would pull 
     for ($x = 1; $x <= 12; $x++) { //loop thru every answer and replace the Q version.
            $answer= $_POST['answer_'.$x]; ///answer to this question
            $formula=str_replace("q".$x, $answer, $formula);
      } //loop thru every answer and replace the Q version.
endwhile;

问题是当我们在 $x=1 时,它正在替换属于 "q10"、"q11" 和 "q12"[=11 的公式中的 q1 =]

也许使用 preg_replace 和负先行模式,如 q1(?!\d),意思是 "q1" 后面没有另一个数字字符。

preg_replace("#q1(?!\d)#","45", "q11-q2-q1-q1");
# q11-q2-45-45

作为解决方法,您可以向后循环:

 for ($x = 12; $x > 1; $x--) { //loop thru every answer and replace the Q version.
        $answer= $_POST['answer_'.$x]; ///answer to this question
        $formula=str_replace("q".$x, $answer, $formula);
  } //loop thru every answer and replace the Q version.

这样Q11修改在Q1之前。