How to loop through, match and replace?

六眼飞鱼酱① 提交于 2019-12-02 03:12:04

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);
} 

You can greatly simplify your code by fetching all the replacement values in one query:

$String = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";
if(preg_match_all("/\{\{[^{}]+\}\}/", $String, $matches)) {
    $Query = "SELECT linkVal, link FROM student WHERE linkVal IN('".implode("','", $matches[0])."')";
    $Result = $con->query($Query);
    if ($rows = $Result->fetchAll(PDO::FETCH_ASSOC)) {
        $NewValue = str_replace(array_column($rows, 'linkVal'), array_column($rows, 'link'), $String);
    }
    echo json_encode($NewValue);
} 

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.

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

$re = '/(?:{{)(.+?)(?:}})/m';
$str = '{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!