str_replace函数无法替换多个值

时间:2019-05-26 04:52:33

标签: php regex

我有一组字符串,并且需要使用str)replace替换它们,因为我们在查询过程中会循环执行,因为查询成功了,需要替换PHP中的每个值。

<?php

include_once("con.php");
$db = new Da();

$con = $db->con();

$lclString = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";

 $lclCount = 1;
 if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {

    foreach ($matches[0] as $match) {

        $lclQuery = "SELECT link, link_value FROM student WHERE link_value = '".$match."'";

        $lclResult = $connString->query($lclQuery);

        while($row = $lclResult->fetch(PDO::FETCH_ASSOC)) {

            $lclNewValue = str_replace($match, $row['link'], $lclString);

            }

        }

        echo json_encode($NewValue);

 } 

?>

这里只有第二次替换。

1 个答案:

答案 0 :(得分:0)

<?php

include_once("con.php");
$db = new Da();

$con = $db->con();

$lclString = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";

 $lclCount = 1;
 if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {
 $lclNewValue = $lclString;
foreach ($matches[0] as $match) {

    $lclQuery = "SELECT link, link_value FROM student WHERE link_value = '".$match."'";

    $lclResult = $connString->query($lclQuery);

    while($row = $lclResult->fetch(PDO::FETCH_ASSOC)) {

        $lclNewValue = str_replace($match, $row['link'], $lclNewValue);

        }

    }

    echo json_encode($NewValue);

 } 

?>