Search code examples
phpregexpreg-replacepreg-match-allregex-group

How to loop through, match and replace?


I have multiple strings with same curly braces I want to replace them as dynamic if I get the count as 1 then need to replace the first occurrence, If count as 2 then replaces the second occurrence as so on until condition satisfies.

<?php

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

$con = $db->con();

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

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

    foreach ($matches[0] as $match) {
        $Count++;
        $Query = "SELECT link FROM student WHERE linkVal = '".$match."'";
        $Result = $con->query($Query);

        if($row = $Result->fetch(PDO::FETCH_ASSOC)) {

            $NewValue = preg_replace("/\{\{[^{}]+\}\}/", $row["link"], $String);

        }
    }

        echo json_encode($NewValue);

 } 


?>

If first occurrence the {{ONE}} should replace with new value with $row["link"], Secondly replace {{TWO}} With New value so on.


Solution

  • Within the loop on each match, instead of using preg_replace, I suggest you to use str_replace:

    if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {
        $NewValue = $String;
        foreach ($matches[0] as $match) {
            $Count++;
            $Query = "SELECT link FROM student WHERE linkVal = '".$match."'";
            $Result = $con->query($Query);
    
            if($row = $Result->fetch(PDO::FETCH_ASSOC)) {
                $NewValue = str_replace($match, $row["link"], $NewValue);
                //          ^^^^^^^^^^^^^^^^^^
            }
        }
        echo json_encode($NewValue);
    }