How to loop through, match and replace?

后端 未结 5 573
悲哀的现实
悲哀的现实 2021-01-22 13:10

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 t

5条回答
  •  梦毁少年i
    2021-01-22 13:30

    There are a few issues with your code, you need to ensure that the variable in the preg_match_all() is the string your trying to search.

    But the main problem is in the replacement part. You need to replace the current match value ($match) and replace it in a new string - currently you always replace the new match in the original string. Here I create $NewValue from the original string and keep replacing values in that...

    if(preg_match_all("/\{\{[^{}]+\}\}/", $String, $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 = preg_replace("/".preg_quote($match)."/", 
                                  $row["link"], $NewValue);
            }
        }
    
        echo json_encode($NewValue);
    
    }
    

    You should also look into using prepared statements as currently you may be open to SQL Injection problems.

提交回复
热议问题