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

这是我的问题的 TLDR 版本:

有没有办法在字符串“q11-q2”上执行 str_replace(“q1”,“45”,“q11-q2”)不替换“q1” ” “q11”的一部分?


更多详细信息

我正在开发一个财务计算器,用户可以在其中输入财务数据,然后我们会输出结果。由于我不会进入的原因,我们不会将公式编写为代码,我们需要将公式作为字符串保存在表格中。例如,该表的列如下所示:

*((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 时,它正在替换公式中的 q1,它是“q10”、“q11”和“q12”的一部分


皈依舞
浏览 122回答 2
2回答

撒科打诨

可能preg_replace与负前瞻模式一起使用,例如q1(?!\d),表示“q1”后面没有另一个数字字符。preg_replace("#q1(?!\d)#","45", "q11-q2-q1-q1");# q11-q2-45-45

月关宝盒

作为一种解决方法,您可以向后循环:&nbsp;for ($x = 12; $x > 1; $x--) { //loop thru every answer and replace the Q version.&nbsp; &nbsp; &nbsp; &nbsp; $answer= $_POST['answer_'.$x]; ///answer to this question&nbsp; &nbsp; &nbsp; &nbsp; $formula=str_replace("q".$x, $answer, $formula);&nbsp; } //loop thru every answer and replace the Q version.这种方式Q11是以前修改的Q1。
打开App,查看更多内容
随时随地看视频慕课网APP