如何在多个查询中执行多个字符串替换?

时间:2016-05-06 05:33:26

标签: php mysql loops str-replace

我有一个名为$queries的数组,如下所示:

Array ( 
    [0] => SELECT * FROM StudentRecord WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND StudentID = '%SID%'; 
    [1] => SELECT * FROM Student_ApplicationRecord WHERE ApplicationYear = '%YEAR%' AND Session%SESSION% = 1; 
)

我还有第二个名为$variables的数组,如下所示:

$variables = array('YEAR' => 2016, 'SESSION' => 1, 'SID' => $_SESSION['sid']);

我想将$queries中的变量替换为$variables中的正确值。

我尝试了很多解决方案,到目前为止我提出的最好的解决方案是:

foreach ($queries as $query)
    foreach($variables as $key=>$value)
        $newqueries[] = str_replace("%".$key."%", $value, $query);

但是,这只是在每个查询中一次替换一个变量。

即。当我这样做时:

foreach ($newqueries as $query)
    print ($query);

每个查询的结果是:

SELECT * FROM StudentRecord 
WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND SID = '%SID%'; 

SELECT * FROM StudentRecord 
WHERE Year = '%YEAR%' AND Session = '1' AND SID = '%SID%';

SELECT * FROM StudentRecord 
WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND SID = '1234';

我想要的是最终数组$newqueries,如下所示:

Array ( 
    [0] => SELECT * FROM StudentRecord WHERE Year = '2016' AND Session = '1' AND StudentID = '1234'; 
    [1] => SELECT * FROM Student_ApplicationRecord WHERE ApplicationYear = '2016' AND Session1 = 1; 
)

有人可以帮帮我吗?如果之前有人问我,我很抱歉,但我找不到任何类似的问题。

1 个答案:

答案 0 :(得分:3)

由于str_replace()接受$search$replace参数的数组,您可以使用它。

$search = ['%YEAR%', '%SESSION%', '%SID%'];
$replace = ['2016', '1', $_SESSION['id']];
$newQueries = [];
foreach ($queries as $query) {
    $newQueries[] = str_replace($search, $replace, $query);
}