How to loop through, match and replace?

丶灬走出姿态 提交于 2020-01-11 11:25:12

问题


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.


回答1:


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



回答2:


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



回答3:


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.




回答4:


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;


来源:https://stackoverflow.com/questions/56305762/how-to-loop-through-match-and-replace

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