這是我的問題的 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 關注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消