Php 如何替换忽略另一个字符串内部字符串的字符串

Php 如何替换忽略另一个字符串内部字符串的字符串,php,str-replace,Php,Str Replace,以下是我问题的TLDR版本: 在字符串“q11-q2”上执行str_替换(“q1”、“45”、“q11-q2”)不会替换“q11”的“q1”部分的情况下,是否有任何方法可以执行stru替换? 更多详细信息 我正在开发一个财务计算器,用户在其中输入财务数据,然后我们将结果吐出来。由于这个原因,我不想讨论,我们不把公式写成代码,我们需要把公式作为字符串保存在表中。例如,表中的列如下所示: *((q2/4)*0.25)49 q10/(q2/4) 我需要将问题1至12的答案插入公式中,其中分别表示

以下是我问题的TLDR版本:
在字符串“q11-q2”上执行str_替换(“q1”、“45”、“q11-q2”)不会替换“q11”的“q1”部分的情况下,是否有任何方法可以执行stru替换?

更多详细信息
我正在开发一个财务计算器,用户在其中输入财务数据,然后我们将结果吐出来。由于这个原因,我不想讨论,我们不把公式写成代码,我们需要把公式作为字符串保存在表中。例如,表中的列如下所示:
*((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;

$query=///这里我要选择每个公式
而($row=mysqli\u fetch\u数组($query)):
$formula=$row['formula']///会拉

对于($x=1;$x可能使用
preg\u替换为类似
q1(?!\d)
的负先行模式,意思是“q1”后面没有另一个数字字符

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

可能使用
preg\u 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.

这样在
Q1
之前修改
Q1

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

 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.

这种方法在
Q1
之前修改
Q1

你能编辑公式吗?给变量一个像
({Q1}/2)
这样的唯一包装器,这样你就可以用
“{q.$x.}”来替换了。
你能编辑公式吗?给变量一个像
({Q1}/2)
这样你就可以用
“{q.$x.}”来替换了。