如何循环、匹配和替换? [英] How to loop through, match and replace?

查看:47
本文介绍了如何循环、匹配和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个带有相同花括号的字符串,我想将它们替换为动态字符串,如果计数为 1,则需要替换第一次出现,如果计数为 2,则替换第二次出现,依此类推,直到条件满足.

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

 } 


?>

如果第一次出现,{{ONE}} 应该用 $row["link"] 替换为新值,其次将 {{TWO}} 替换为新值,依此类推.

If first occurrence the {{ONE}} should replace with new value with $row["link"], Secondly replace {{TWO}} With New value so on.

推荐答案

在每次匹配的循环内,我建议您使用 str_replace 代替 preg_replace:

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

这篇关于如何循环、匹配和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆