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
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.