How to loop through, match and replace?

后端 未结 5 572
悲哀的现实
悲哀的现实 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-22 13:36

    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;
    
    0 讨论(0)
  • 2021-01-22 13:39

    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);
    } 
    
    0 讨论(0)
  • 2021-01-22 13:44

    You can use preg_replace_callback to iterate through your matches.

    e.g.

    $str = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";
    $replaced = preg_replace_callback('/{{([^{}]*)}}/', function($match) {
    // $match[1] contains the current match (first capture group) e.g. ONE
    // return your replacement for the current match, e.g. reversed string ENO
    return strrev($match[1]);
    }, $str);
    echo $replaced;
    

    Output will be ENO OWT EERHT RUOF EVIF XIS

    0 讨论(0)
  • 2021-01-22 13:45

    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);
    } 
    
    0 讨论(0)
提交回复
热议问题