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.
The expression we might wish to design here can be like one of these:
which is only using capturing groups
()
.DEMO 1
and here we can use non-capturing groups
(?:)
, if we do not wish to keep the{{
and}}
.DEMO 2
Then, we could simply do the
preg_replace
that we wanted to do.Test
You can greatly simplify your code by fetching all the replacement values in one query:
Within the loop on each match, instead of using
preg_replace
, I suggest you to usestr_replace
: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...You should also look into using prepared statements as currently you may be open to SQL Injection problems.