这里是我问题的TLDR版本:
在字符串"q11-q2“上执行”str_replace“( "q1”、"45“、"q11-q2")而不替换"q11”的“q1”部分,有什么方法可以做到吗?
详细信息
我正在开发一个金融计算器,用户可以输入金融数据,然后我们就会说出结果。由于我不能进入的原因,我们不把公式写成代码,我们需要将公式作为字符串保存在表中。例如,表中有如下列:
\*((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“中的公式中的q1
发布于 2019-12-06 21:17:51
也许使用preg_replace时有一个负的查找模式,比如q1(?!\d),意思是"q1“后面没有另一个数字字符。
preg_replace("#q1(?!\d)#","45", "q11-q2-q1-q1");
# q11-q2-45-45发布于 2019-12-06 21:21:07
作为一种解决办法,您可以向后循环:
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之前就被修改了。
https://stackoverflow.com/questions/59220423
复制相似问题