这是我的问题的 TLDR 版本:有没有办法在字符串“q11-q2”上执行 str_replace(“q1”,“45”,“q11-q2”)不替换“q1” ” “q11”的一部分?更多详细信息我正在开发一个财务计算器,用户可以在其中输入财务数据,然后我们会输出结果。由于我不会进入的原因,我们不会将公式编写为代码,我们需要将公式作为字符串保存在表格中。例如,该表的列如下所示:*((q2/4)*0.25) 49q10/(q2/4)我需要将问题 1 到 12 的答案插入到公式中,其中分别表示 q1,q2,...q10,q11,q12。为此,我正在做:$query= ///here i'd select each formulawhile ($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”的一部分
2 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
可能preg_replace与负前瞻模式一起使用,例如q1(?!\d),表示“q1”后面没有另一个数字字符。
preg_replace("#q1(?!\d)#","45", "q11-q2-q1-q1");
# q11-q2-45-45
月关宝盒
TA贡献1772条经验 获得超5个赞
作为一种解决方法,您可以向后循环:
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。
- 2 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消
