How to loop through, match and replace?

后端 未结 5 575
悲哀的现实
悲哀的现实 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
    } 
    

提交回复
热议问题